Skip to content
Advertisement

Calculate Number from a loop increment number

+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 2 | 1 | 0 |
+---+---+---+
| 3 | 2 | 0 |
+---+---+---+
| 4 | 0 | 1 |
+---+---+---+
| 5 | 1 | 1 |
+---+---+---+
| 6 | 2 | 1 |
+---+---+---+
| 7 | 0 | 2 |
+---+---+---+
| 8 | 1 | 2 |
+---+---+---+
| 9 | 2 | 2 |
+---+---+---+

The code I am trying

var loop = 1;
while(loop < 10) {
    console.log(loop, loop%3, "I can't calculate this")
    loop++;
}

I have a loop increment variable loop and it counting 1,2,3,4,5….

I need to calculate 2 number from incremental variable: one is rounding 0,1,2 (loop % 3) I can do this but other 0,0,0 or 1,1,1

I mean I need to hold a number according to my round number.

Advertisement

Answer

Fixed your code ((loop-1)%3) and you just need a division with rounding down:

var loop = 1;
while(loop < 10) {
    console.log(loop, (loop-1)%3, Math.floor((loop-1)/3))
    loop++;
}

Some other languages support “integer division”, where the Math.floor thing would not be necessary.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement