Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my modulus logic for this loop correct?

So here's the pattern i'm looking for

out of a finite set, I want to retrieve the first 2 values for one set, then followed by the next 4 for another set, then 2 for that first set, and then 4 for the other set, and so on..

grab 2 | grab 4 | grab 2 | grab 4 ...

$count = 0;
foreach ($listing as $entry){
  if ($count % 4 == 0){
       // add to 4-item set
  } else if ($count % 2 == 0){
       // add to 2-item set
  }
  $count++;
}

My confusion is that when $count%4=0 then $count%2 will also = 0.

So should i be safe by not reaching the wrong modulus case (since both are true for any arbitrary number divisible by 4) by checking first if $count%4 == 0?

like image 982
Atticus Avatar asked Jan 29 '26 00:01

Atticus


1 Answers

If I get it right, your desired distribution is actually:

A A, B B B B, A A, B B B B, A A, B B B B, ...

So you want to group them into six and then pick the first two into basked A, the other four into B:

if ($count % 6 < 2){
   // add to 2-item set
}
elseif ($count % 6 < 6){
   // add to 4-item set
}

Splitting it into if/elseif will ensure that the items only end up in either one. The < n comparison on the % 6 distribution would mean:

$count % 6 =    0  1  2  3  4  5  0
        if =   <2 <2 <6 <6 <6 <6 <2
    basket =    A  A  B  B  B  B  A
like image 194
mario Avatar answered Jan 30 '26 12:01

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!