Constraint to Generate 10 bit number with set bits such that no set bits are together

Write a constraint to generate a random value of 10 bits with set bits and no two set bits should be next to each other.
My idea to solve this problem was to use replication operator to randomly generate multiples of 2’b10.
Is there any better approach to solve it?

class sample;
  rand bit [9:0] x;
  rand bit [1:0] as;
  constraint a{
    as inside {[1:5]};
  }
  function void post_randomize();
    x = {as{2'b10}};
  endfunction
endclass


module tb;
  sample s = new();
  
  initial begin
    repeat(10) begin
    s.randomize();
    $display("%b",s.x);
    end
    
  end
endmodule
1 Like

There are some problems with your code.

I ran it on 2 simulators, and I got compile errors. When I ran it on a 3rd simulator, I got a compile warning.

You declared “as” as a 2-bit value, which means it can only take on values 0-3. It can not be 4 or 5, as your constraint allows. This means that you never set the MSB’s of “x” to 1.

Here is one way which meets your spec and runs on multiple simulators:

class sample;
    rand bit [9:0] x;
    constraint c {
        foreach (x[i]) if (i<9) {x[i], x[i+1]} != 3;
    }
endclass
1 Like

This was my first thought without reading previous ideas.


rand bit[9:0] x;

constraint gaps_c {
	foreach (x[i]) {
		if (i > 0) {
			!(x[i] && x[i-1];
		}
	}
}

nimrodw1: Did it work for you when you ran a simulation? It looks like there is a syntax error.

Try ::

class main;
    
    rand bit[9:0] b;
    
    constraint ONES {  ( b & ( b << 1 ) ) == 0 ; }
    
  endclass  

I haven’t tested with random seeds, using the default seed output is as per intention.

3 Likes
class sample;
  rand bit [9:0] x;
  
 constraint c
  {
    $countones(x) > 1;
    foreach(x[i])
    {
      if(i < 9 && x[i] == 1)
        x[i+1] != 1;
    }
  };
endclass


module tb;
  sample s = new();
  
  initial begin
    repeat(2) begin
    s.randomize();
    $display("%b",s.x);
    end
    
  end
endmodule
1 Like

@Kushal_Nijalingappa, your example only produces 2 out of the 145 possible valid solutions.

Thanks for pointing it out. I had read it wrongly. My apologies. Edited the code now. @dave_59