I have an array list containing 5 bulbs. I can iterate throuh them like this
for(Bulb bul : list){
System.out.println(bul.id);
}
No a bulb is switched off/on. The effect is that its neighbourg bulbs a switch too.
My problem is that when the last or 4th bulb are switched I need to determine its neighbours. Since I have 5 bulbs this would work.
int bulbIdClicked = 3;
if(bul.id == (bulbIdClicked + 1)%5)
if(bul.id == (bulbIdClicked - 1)%5)
For 3 it would give me 2 and 4 as neighbours. But when 4 is switched it gives me 3 and 0 ans neighbours where 0 should be 5.
How can I solve that problem?
If you have a bulb ID ranging from 0 to 4, the best way to get the next and previous IDs is to use:
This is language-agnostic since not all languages treat modulus operators on negative numbers the same. You can see that stepping forward 4 from 4 (for example) gives you: 0, 1, 2, 3 which is the same as a step backwards.
However. modulus really only works on zero-based values. Since you have one-based values, you can subtract one first, do the relevant addition/modulo, then add one again.
These simplify down to:
Using those formula, you get:
as expected.
That’s about as optimised as you’re likely to get without a lookup table. You can use the same approach for any roll-over size (not just 5), you just have to change the modulo and what you add.
If the indexes range from 1 to
N, its:where the figures inside
[]are constant based on the number of indexes.