Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a for loop that will pick up a count where it left off?

I know this is very silly question, but I am struggling to find this logic. I am trying to work on this very basic for loop to achieve this result

0 - 0
0 - 1
0 - 2
0 - 3
0 - 4
0 - 5
0 - 6
0 - 7
0 - 8
0 - 9
0 - 10
0 - 11

1 - 12
1 - 13
1 - 14
1 - 15
1 - 16
1 - 17
1 - 18
1 - 19
1 - 20
1 - 21
1 - 22
1 - 23

2 - 24
2 - 25
2 - 26
2 - 27
2 - 28
2 - 29
2 - 30
2 - 31
2 - 32
2 - 33
2 - 34
2 - 35

The inner loop should continue from the number where the first inner loop was cut done. in the first iteration it left off at 11, the second time it comes to the inner loop it should go from 12 - 24 and so forth.

var count = 0;
var val = 0;
for(i = 0; i < 3; i++) {
    for(j = 0; j < count + 12; j++) {
        console.log(i + " - " + j);       

    }
    val = j;
    count = count + j;
    console.log(count);
}
like image 831
user525146 Avatar asked Jun 03 '15 20:06

user525146


2 Answers

There are several "clever" answers here. I'd stick with a "simple to read and simple to debug" answer. Here's a solution in C# that should be simple enough to translate:

int k = 0;
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 12; j++)
    {
        Console.WriteLine(i + " - " + k++);
    }
    Console.WriteLine();
}

Organizational Skills Beat Algorithmic Wizardry

like image 94
JMD Avatar answered Nov 07 '22 22:11

JMD


You don't need 2 loops, you can achieve this with a single loop:

for (var i = 0; i < 36; i++){
  console.log(Math.floor(i/12) + " - " + i);  
}

If you don't like Math.floor, you can use the double bitwise not operator to truncate the float:

for (var i = 0; i < 36; i++){
  console.log(~~(i/12) + " - " + i);  
}
like image 56
WakeskaterX Avatar answered Nov 07 '22 22:11

WakeskaterX