Constraint number generated with bits control

I want to write a constraint such that new no generated has only 3 bits changes compared to previously generated no .
For example , no is 5’b00010 then next no should generated be 000101 or 11110 or 01001 etc …

In reply to mehul_1111:

This seems to becoming a popular interview/homework question

https://verificationacademy.com/forums/systemverilog/constraint-32-bit-addr-be-different-prev-addr-2-bits

class A;
  rand bit[4:0] addr;  
 constraint addr_c {
   $countones(addr ^ const'(addr)) == 3;
 }
endclass
module abc;
  A a1;
  
  initial begin
    for(int i=0;i<10;i++) begin
      a1=new();
      if(!a1.randomize())
        $error("randomization failed");
      $display("%b",a1.addr);
    end
  end
endmodule

I tried the above code but I got output as below:

# vsim -voptargs=+acc=npr
# run -all
# 10011
# 10011
# 11001
# 01110
# 11001
# 10110
# 01101
# 10011
# 10011
# 10110
# exit

here first 2 numbers are same. Am I missing something?

In reply to juhi_p:

Am I missing something?

Yes, your for-loop re-constructs a1 every iteration. So addr starts from 0 every randomization. Move the call to new() before the for-loop.

In reply to dave_59:

Thanks Dave. I got it.

In reply to dave_59:

In reply to mehul_1111:
This seems to becoming a popular interview/homework question
Constraint for 32 bit addr to be different than prev addr by 2 bits - SystemVerilog - Verification Academy

Indeed, I recently learned that one of our past employees had it as a standard interview question. Unfortunately, as of this post it appears that only 1 of the 4 simulators on edaplayground supports it. Looking at at section 6.24.1 of the 2017 LRM it’s not entirely obvious to me it’s supposed to be used this way, and the only const’ examples presented are for assertions.

Your example (below) is a novel method for ensuring a 2-bit result, but I’ve honestly only seen this implemented with either an intermediate signal (sized appropriately), or by wrapping it in a {} “concat part-select”.

EDIT: also only supported by Questa, and after a quick test actually resulted in “3”, not the “0” as you claimed (version 2021.3).


  function void test2();
    bit a = 1;
    bit [1:0] b = 3;
    bit [2:0] c;
    bit [2:0] d;
 
    $display("a: %x b: %x c: %x d: %x", a, b, c, d);
    c = a + b; // c would be 3'b4
    $display("a: %x b: %x c: %x d: %x", a, b, c, d);
    c = const'(a + b); // c would be 3'b0
    $display("a: %x b: %x c: %x d: %x", a, b, c, d);    
    d = const'(a + b);
    $display("a: %x b: %x c: %x d: %x", a, b, c, d);
    
  endfunction : test2

a: 1 b: 3 c: 0 d: 0

a: 1 b: 3 c: 4 d: 0

a: 1 b: 3 c: 4 d: 0

a: 1 b: 3 c: 4 d: 4