How do I check that x is 1 greater (ahead) of y in a modulo sense (mod 3)?
This is when x = 0 and y = 2, when x = 1, y = 0 and when x = 2, y = 1.
I tried testing like this:
php -a php > $x = 0; php > $y = 2; php > echo ($x - $y) % 3; -2 php > $x = 1; php > $y = 0; php > echo ($x - $y) % 3; 1 php > $x = 2; php > $y = 1; php > echo ($x - $y) % 3; 1
It is not working for the case where x = 0 and y = 2. How can I calculate this so that $x is ‘ahead’ of $y by 1 in a modulo sense?
Advertisement
Answer
I will first explain my understanding of your following sentence:
How do I check that x is 1 greater (ahead) of y in a modulo sense (mod 3)?
Following the examples provided, I assume you mean that, if 1 is added to $y, and we take the mod 3 of $y, we would get the mod 3 of $x.
With that in mind, we could write the following code, witch would return true if $x is “ahead” of $y by 1. (I hope you can abstract that example to whatever situation you are facing):
function check($x, $y, $mod) { return $x % $mod == ($y + 1) % $mod; } //$x = 0 and $y = 2 echo check(0,2,3); //returns true //$x = 1 and $y = 0 echo check(1,0,3); //returns true //$x = 2 and $y = 1 echo check(2,1,3); //returns true //$x = 0 and $y = 1 echo check(0,1,3); //returns false because $x is 2 "ahead" of $y
If you want a more generalized version of the function, with an arbitrary difference, you can use this (it should work with positive and negative differences):
function check($x, $y, $mod, $diff) { return $x % $mod == ($y + $diff) % $mod; }