# Why this code not producing the desired result for the given question- "Constraint to generate 0, 1, x and z randomly"

**URL:** <https://verificationacademy.com/forums/t/why-this-code-not-producing-the-desired-result-for-the-given-question-constraint-to-generate-0-1-x-and-z-randomly/46226>\
**Category:** SystemVerilog\
**Tags:** constraint-randomization\
**Created:** [February 20, 2024, 9:48am UTC](https://verificationacademy.com/forums/t/why-this-code-not-producing-the-desired-result-for-the-given-question-constraint-to-generate-0-1-x-and-z-randomly/46226 "2024-02-20T09:48:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vishwajeetsinh](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/vishwajeetsinh/32/1415_2.png) [@vishwajeetsinh](https://verificationacademy.com/forums/u/vishwajeetsinh)\
**Post date:** [February 20, 2024, 9:48am UTC](https://verificationacademy.com/forums/t/why-this-code-not-producing-the-desired-result-for-the-given-question-constraint-to-generate-0-1-x-and-z-randomly/46226/1 "2024-02-20T09:48:48Z")

</div>

```auto
class abc;
  rand logic a;
  
  constraint cons1 { a inside {0,1,x,z};};
  
endclass 

module abc;
  abc a1;
  
  initial begin
    a1=new();
    repeat(10) begin
    	a1.randomize();
      	$display("%d",a1.a);
    end
  end
endmodule 

```

---

<div class="post-metadata">

**Author:** ![cgales](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/c/ccd318/32.png) [@cgales](https://verificationacademy.com/forums/u/cgales)\
**Post date:** [February 20, 2024, 5:20pm UTC](https://verificationacademy.com/forums/t/why-this-code-not-producing-the-desired-result-for-the-given-question-constraint-to-generate-0-1-x-and-z-randomly/46226/2 "2024-02-20T17:20:47Z")

</div>

You can’t use 4-state values when randomizing. You need to use an intermediate variable with a post\_randomize() function:

```auto
class abc;
  
  rand int a_int;
  logic a;
  
  constraint cons1 { a_int inside {[0:3]};};
  
  function void post_randomize();
    case(a_int)
      0: a = 0;
      1: a = 1;
      2: a = 'x;
      3: a = 'z;
    endcase
  endfunction
  
endclass 

module abc;
  abc a1;
  
  initial begin
    a1=new();
    repeat(10) begin
      if (!a1.randomize()) begin
        $display("Randomization failed");
      end
      else begin
        $display("%b",a1.a);
      end
    end
  end
endmodule 

```
