Array locator method (Min and with clause)

Hi

I want to find the min value of the array from first 4 locations only. There is one way to take first 4 elements in a different queue/array then use min function, but if I am trying to do in following manner and I am observing an unexpected result.

Can anyone please explain what is the issue?

module tb;
  int arr[5] = '{4,3,2,1,5};
  int min_val[$];
  
  initial begin
    min_val = arr.min with (item.index < 4);
    $display("min_val %0p",min_val);
  end
  
endmodule

Output : min_val '{5}

The with clause generates the values used to judge which element has the minimum value, not the values to selected. In your example, it creates the array '{0,1,1,1,0}. 0 is the minimum value, and there are two elements associated with that. So either 4 or 5 could have been selected as the minimum value.

Hi Dave, Thanks for the reply.

If that is how it works then it will generate '{1,1,1,1,0} and always select 0th location element which is 5 in this case. Is my understanding correct?

(item.index > 4) : Here why did with clause is generating ‘{0,1,1,1,0} ?

But, Why this works as expected with find method?

selected_vals = arr.find with (item.index < 4);

Thanks

Yes I did make a mistake. Only the last element arr[4] has item.index < 4 which is 0. That makes it the sole minimum value.

The find method is a filter-- it selects elements when the with clause is true. Here’s another example that might make it more clear how these method behave.

int arr[] = {9,8,7,6,5,4,3,2,1};
max_val = arr.max() with ($countones(item));

That returns {7}, because $countones(7) is 3, and all the other elements are 1 or 2.

max_val = arr.max() with ($countones(item.index));

That returns {2} because arr[7] has the value 2.

1 Like

Thanks Dave. I got it now.