$Countones in a 2 dimensional array

I am trying to count the number of ones in a 2D array as below. The below code works as expected but is there a better way without using a function?

   class c1;
        rand bit [7:0] w [5];
        rand int one [5];

        rand int length;

        constraint c1 {
		foreach(w[i])
            	   one[i] == count_ones(w[i]);
		length == one.sum();	
        }

        function int count_ones (bit [7:0] data_in);
            count_ones = $countones(data_in) ;
        endfunction

    endclass

module dut();

    initial begin
        c1 a;
        a = new();

       
            if(a.randomize())
                foreach(a.w[i]) $display("w is %b", a.w[i]);
                foreach(a.one[i]) $display("one's are %d", a.one[i]);
                $display("length is %d", a.length);
       
    end
endmodule
constraint c1 {
		foreach(w[i])
            	   one[i] == $countones(w[i]);
		length == one.sum();	
        }
1 Like

Is there a $countones() equivalent that would work on a 2D array?

For eg. if I had the 2D array as below]. The ‘length’ should be the sum of $countones() for each w[i][j].

rand bit [7:0] w[5][5];
rand int length;

lenght == w.sum() with ($countones(item));