Reputation: 7273
I want to start my for loop at a certain number, and make it loop. Like this:
5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4
If the maximum number is 10 and it starts at 5.
The reason is because I want to loop through every tile in my game in a certain order (top to down, then go right).
I have tried the following but it skips one number:
for(var i = position[0]+1; i != position[0]; i++){
for(var j = position[1]+1; j != position[1]; j++){
if(j > 11){
j = 0;
}
if(i > 23){
i = 0;
}
if(levelMap[i][j] == type){
return position;
}
trace("j" + j);
}
trace(i);
}
Thanks
Upvotes: 0
Views: 309
Reputation: 882806
If you want a sequence like 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4
(where the starting point can be any number in that set), you don't need fancy loop constructs.
You can just use a normal loop with the modulo operator, something like (pseudo-code since one of the tags was language-agnostic
):
start = 5
for i = 0 to 10
use_i = (start + i) % 11
// do something with use_i rather than i.
next i
This will iterate use_i
from 5 to 4, cycling back to 0 after 10.
Upvotes: 5
Reputation: 15955
This could be done with i alone; however, trying to use your example maybe something like:
package
{
import flash.display.Sprite;
public class Test extends Sprite
{
public function Test()
{
super();
for (var i:uint = 0, j:uint = 5; i < 11; i++, j = (5 + i) % 11)
{
trace("j = " + j);
}
}
}
}
Upvotes: 1
Reputation: 27886
Your question is a bit confusing, but I do see a couple of possible errors based off of the order of numbers you said you're trying to achieve.
First, if you want the highest possible number for j
to be 10
, your conditional should be for (j > 10)
, not for (j > 11)
. The way it is now allows for j
to iterate as 11
once.
Next, in that same conditional, you'll want to set j
to -1
, not 0
. This is because j
will increment on the next loop, and setting it to 0
means on next loop j
will actually equal 1
, and skip the 0
iteration (which may be what you meant when you said it "skips one number"). So it'll be:
if (j > 10)
{
j = -1;
}
Hope that helps.
Upvotes: 1