rzfzr
rzfzr

Reputation: 43

Loop around an array

Let's say I have an Array:

arr[3]={0,1,2};

and I am generating a Random value:

int r = Random.Range(0,4);

And in my code just after that I want to use:

print(arr[r-1]+arr[r]+arr[r+1]);

In this case it will only work if arr[r] is 1, because if r=0 then r-1 will be -1 , what can I do so if I increment the last index, it goes back to a certain point? So that if r=2, so arr[r]=2, arr[r+1]=0 , and arr[r+4] is also 0 because it did an extra loop.

I know I could use ifs, if r=0 then r-1=3 but it's less than ideal. Thanks

Upvotes: 0

Views: 100

Answers (2)

Enigmativity
Enigmativity

Reputation: 117010

Here's something that I think you can work with:

var random = new Random();

var arr = new [] { 0, 1, 2 };

for (var i = 0; i < 20; i++)
{
    int r = random.Next(1, 1 + arr.Length);
    Console.WriteLine(String.Join(", ", (r - 1) % 3, r % 3, (r + 1) % 3));
}

That produces:

1, 2, 0
2, 0, 1
2, 0, 1
1, 2, 0
2, 0, 1
2, 0, 1
1, 2, 0
1, 2, 0
2, 0, 1
1, 2, 0
1, 2, 0
1, 2, 0
2, 0, 1
1, 2, 0
1, 2, 0
1, 2, 0
0, 1, 2
1, 2, 0
1, 2, 0
0, 1, 2

Upvotes: 1

Hung Nguyen
Hung Nguyen

Reputation: 301

You can try modulus %. I'm not too sure if the operation will always return a positive value, but you can always do r = random.range(3,7);, and then use r-1 % 3 etc.

Upvotes: 1

Related Questions