In reply to verif_eng_20:

It might help to shrink your code into something more manageable, like 3 consecutive bits in a 6-bit vector. Then unroll the foreach constraints manually.

class a;
rand bit[5:0] var1;
constraint c_var1{
$countones(var1) == 3;
foreach(var1[i]){
if(var1[i] && i<=3)
{var1[i],var1[i+1],var1[i+2]} == 3'b111;
}
}
endclass
module test;
a a_h;
initial
begin
a_h = new;
repeat(20) begin
void'(a_h.randomize());
$display("a_h.var1:%6b",a_h.var1);
end
end
endmodule

Then unroll the foreach loop into 6 set of constraints

if(var1[0] && 0<=3)
{var1[0],var1[1],var1[2]} == 3'b111;
if(var1[1] && 1<=3)
{var1[1],var1[2],var1[3]} == 3'b111;
if(var1[2] && 2<=3)
{var1[2],var1[3],var1[4]} == 3'b111;
if(var1[3] && 3<=3)
{var1[3],var1[4],var1[5} == 3'b111;
if(var1[4] && 4<=3)
// always false
if(var1[5] && 5<=3)
// always false

This can be further reduced to

if(var1[0])
{var1[2:0]} == 3'b111;
if(var1[1])
{var1[3:1]} == 3'b111;
if(var1[2])
{var1[4:2]} == 3'b111;
if(var1[3])
{var1[5:3]} == 3'b111;

Now you should be able to see why only var1[3] can be true and still satisfy the other constraint $countones(var1) == 3;