I got some question that i cannot wrap my head around I want to create a for loop that start from certain index(not 0) and looping back from 0 until it reach that certain index.
now i know how to start at certain index Like this ->
int startIndex = 3
int max = 5
for(int i = startIndex; i <= max ; i )
{
Debug.Log(i);
}
that code will return me:
3
4
5
But how do i iterate it back again? what i want to have is like this order:
3
4
5
0
1
2
CodePudding user response:
You can use the modulo operation (%
). It calculates the remainder of an integer division.
E.g. 8 % 6 = 2
, because 8 / 6 = 1, remainder = 2
.
int n = 6;
int startIndex = 3;
for (int i = startIndex; i < startIndex n ; i )
{
Debug.Log(i % n);
}
% 6
will subtract 6 until the number becomes smaller than 6.
i | i % 6 |
---|---|
3 | 3 |
4 | 4 |
5 | 5 |
6 | 0 |
7 | 1 |
8 | 2 |
The modulo operation is often used to create a circular behavior.
CodePudding user response:
int startIndex = 3;
int max = 5;
for (int i = startIndex; i <= max; i )
{
if (i == 5)
{
Console.WriteLine(i);
i = 0;
}
else if (i == 0)
{
i = 3;
}
Console.WriteLine(i);
}
I think this should work. Just Write Debug.Log instead of Console.WriteLine()
CodePudding user response:
You can use Enumerable class and method Range, which can produce values.
First parameter mean first number of sequence and the second one how many of numbers you want.
var myInts = Enumerable.Range(startIndex, max - startIndex 1).Concat(Enumerable.Range(0, startIndex)).ToArray();
UPDATE:
I realize, that concat method is very harm for memory, in result garbage collector must clean up 3 sequenses, so next code is much better:
var myInts = Enumerable.Range(0, max 1).OrderBy(i => i < startIndex).ToArray();
In this case, sequence created once and then just sorted by rule.
CodePudding user response:
This is quite clean, and only uses simple incrementation:
const int startIndex = 3;
const int max = 5;
var i = startIndex;
do
{
Console.WriteLine(i);
} while ((i = i 1 <= max ? i 1 : 0) != startIndex);
This prints:
3
4
5
0
1
2
i = i 1 <= max ? i 1 : 0
this logic works well because it tries to increment until max
, otherwise starts from zero and stops at startIndex
, without unnecessary memory allocations.