Constraint an array to have at least n pairs of consecutive x values

Hi All,
I want to constraint an array / a queue to have at least n pairs of consecutive x values.

For example:
int values = '{1,2,2,3,5,1,2,2,2};
In the above array (1,2), (6,7), (7,8) index pairs have value “2”. So there are 3 pairs of value “2”.

I want to constrain this number of pairs to a specific value.

I expect something like below, (generated from Bard and modified: not syntactically correct)


rand int values[10];

constraint values_c{
  int pair_count;
  foreach (values[i]) {
    if (i < values.size()-1) {
      if (values[i] == 2 && values[i+1] == 2) {
        pair_count ++;
      }
    }    
  }
  pair_count == 3;
}

Could someone please explain me how to implement the above constraint?

Thanks in advance.

In reply to tharindu:

Constraints are not procedural code, they are equations.

Although you might be able to get this into a single sum() equation, using a helper array ‘pairs’ i think is easier to comprehend.

module top;
  class A;
    rand int values[10], pairs[10];
    int pair_count = 3;
    int selected_value = 2;
    constraint values_c {
      foreach (values[i])
        if (i > 0) pairs[i] == 
          (values[i-1] == selected_value && values[i] == selected_value);
      pairs[0] == 0;
      pairs.sum() == pair_count;
    }
  endclass
  
  A a = new;
  initial repeat(10) begin
    assert(a.randomize);
    $display("%p",a.values);
    $display("%p",a.pairs);
    
  end
endmodule

Hey Dave,
I tried with the sum() function:

 class Example;
    rand bit[4:0] num_arr[10];
    rand int x;
    rand int n_pairs;

    constraint c1 {x inside [{2:4}];}
    constraint c2 {n_pairs inside {[3:4]};}

    constraint c3{foreach(num_arr[i]){
     i <=8 ->  num_arr.sum (with (num_arr[item.index-1] && num_arr[item.index] == x)) == n_pairs;
    }}; //index out of bounds error although I have i <= 8; why?
  endclass

  module TB;
    Example E;
    initial begin
      E = new();
      assert(E.randomize());
      $display("%p", E.num_arr);
    end    

  endmodule```

It looks like i<=8 does not kick in for the c3 constraint; also, sum() applies to ALL elements of the array and cannot be selective? Experimenting and trying to understand. Appreciate your inputs. Thank you.

Two problems with your constraint c3

  • i iterates from 0 to 9. You either need to change the condition to i>0 or the use index+1 instead of index-1.
  • The result of a logical and (&&) has bit width of 1, so the sum is only 1-bit wide. You need to cast it to a larger width.
 constraint c3{foreach(num_arr[i]) i <=8 ->  
    num_arr.sum() with (
        int'(num_arr[item.index+1]==x && num_arr[item.index] ==x)
) 
=  n_pairs;
}