Joel
Joel

Reputation: 2721

Tricky conditional maths

This one is tricky to me:

I have four groups of 8 LEDs. A is 1-8, B is 9-16, C is 17-24, and D is 25-32.

I'm trying to figure out how to write a conditional where

i = 0 //this would be the LED number

loop {
 i = //gets updated here
 if (i is in the first group) {
    //  do stuff
 }  else {
    //do other stuff
 }
}

Basically, I need to check an LED before it is turned off to see if it is in the same group as the new LED that is being lit.

If it is in the same group, it will be turned off, if it is NOT in the same group it needs to stay on.

So math-wise I need to see if the number is between a certain range. I guess I could just write four versions

if (i >=8)
...
if(i <=9 && >=16)
...

etc, but that doesn't seem very tidy...

Upvotes: 0

Views: 77

Answers (2)

Bryan
Bryan

Reputation: 1241

GetLedGroup(i)
  string[] arrLed = {"A","B","C","D"};
  return arrLed[Math.floor(i/8)-1];

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799190

Use integer division. Subtract 1 from both values then integer divide by 8. If they're the same result then both LEDs are in the same bank.

def samebank(i, j):
  return ((i - 1) // 8) == ((j - 1) // 8)

Upvotes: 5

Related Questions