s_p
s_p

Reputation: 4693

iterate through a loop multiple numbers at a time

how can i iterate through a loop more than 1 index at a time and stop when the highest index reaches a certain number?
I saw this article but could'nt translate this into javascript.

var i,j,k;
i = j = k = 0;
while(k<100){
    j = i+1;
    k = i+2;
    console.log(i+' '+j+' '+k); // k reaches 101
    i = i+3;  
}

Upvotes: 1

Views: 258

Answers (4)

Steven Wexler
Steven Wexler

Reputation: 17279

Many of these answers are good answers. However, none of these answers offer a solution where the last (non full) iteration is included if the limit of the loop (100 in this case) isn't divisible by the number of items per iteration (3 in this case). In other words, non of the answers log "99" for the OP. So I added a solution that satisfies this criteria and is general for any limit or itemsPerIteration where limit and itemsPerIteration are natural numbers.

function multipleItemsForLoop(limit, itemsPerIteration, callback) {
    var loop = function(i) {
        var numItemsThisIteration = Math.min(limit - i, itemsPerIteration);
        if(numItemsThisIteration <= 0) {
            return;
        }
        var itemIndecies = [];
        for(var x = 0; x < numItemsThisIteration; x++) {
            itemIndecies.push(i+x);
        }

        callback(itemIndecies);

        loop(i+itemsPerIteration > limit && numItemsThisIteration === itemsPerIteration ? i + 1 : i + itemsPerIteration);
    }

    loop(0);
}

multipleItemsForLoop(100, 3, function (itemIndecies) { console.log(itemIndecies); } );

Upvotes: 2

Edmund Joseph
Edmund Joseph

Reputation: 130

If I understood your problem correctly, you want it to stop before k reaches > 100.

If so change your while loop into a do... while loop. That way, it evaluates the condition at the end of an iteration.

do{
        j = i+1;
        console.log(i+' '+j+' '+k);
        k = i+2;
        i = i+3;
} while (k<100);

Upvotes: 1

Bergi
Bergi

Reputation: 664346

It seems like you want

var i = 0,
    j = 1,
    k = 2;
while (k < 100) {
    console.log(i+' '+j+' '+k);
    i += 3;
    j += 3;
    k += 3;
}

Or, more concise, in a for-loop:

for (var i=0, j=1, k=2; k < 100; k=1+(j=1+(i+=3))) {
    console.log(i+' '+j+' '+k);
}

Yet, usually you wouldn't use three variable for that. Instead, just make it

for (var i=0; i<100-2; i+=3) {
    console.log(i+' '+(i+1)+' '+(i+2));
}
// or
for (var k=2; k<100; k+=3) {
    console.log((k-2)+' '+(k-1)+' '+k);
}

Upvotes: 1

Paul S.
Paul S.

Reputation: 66324

Perhaps you wanted something more of the form

var i, j, k = 0;
while (k < 99) {
    k = (j = (i = k + 1) + 1) + 1;
    console.log('i', i, 'j', j, 'k', k);
}

so you get

i 1 j 2 k 3
i 4 j 5 k 6
...
i 97 j 98 k 99

Upvotes: 1

Related Questions