I have been trying to solve this constraints problem given below

Create a class for a graphics image that is 10x10 pixels. The value for each
pixel can be randomized to black or white. Randomly generate an image that is,
on average, 20% white. Print the image and report the number of pixels of each
type.

I tried solving it where I generate an array of 100 elements, where each element is restricted to 0 or 1 and then the sum of the array should be greater than 20, since I’m assuming 1 represents white. But I don’t think that is correct, could anyone else give a better solution?

class graphicsimage;
  rand integer image[100];
  constraint c1 {foreach (image[i])
    image[i] inside {[0:1]};
                 image.sum() < 20; }
endclass

module tb;
  graphicsimage gi;
  initial begin
    gi = new();
    repeat(10) begin
    gi.randomize();
      $display("%d",gi.image.sum());
      $display("%p",gi.image);
  end
  end
endmodule

In reply to hsam:

@hsam, your logic wont work for all seeds.

class packet;
  
  rand bit[9:0] matrix[9:0];

  constraint c2{
    foreach(matrix[ii,])
      $countones(matrix[ii]) == 2; 
  }
   
endclass : packet

module test;
  
  packet pkt;
  int b=0,w=0;
  
  initial begin
    pkt = new();
    pkt.randomize();
   
    foreach(pkt.matrix[ii,])
      $display("%10b", pkt.matrix[ii]);
  
       
  end
  
  
endmodule

In reply to chindanoor:

Your constraint would always give 2 ones in each row whereas the question expects
to have 20% ones across 100 pixels . So there is a chance of more than 2 ones
in each row .

A better solution would be ::


class packet;
 
  rand bit[9:0] matrix[9:0];
 
  constraint c2{
      matrix.sum()  with  (  $countones( item  )  )  == 20 ; 
               }
 
endclass : packet