Created
March 13, 2022 11:30
-
-
Save NovemberDev/876f249d240c199fb270a79de35b16e3 to your computer and use it in GitHub Desktop.
Infinitely loops an array in both directions while respecting the array bounds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var index = 0; | |
var arr = new int[] { 1, 2, 3, 4 }; | |
for(int i = 0; i < 20; i++) { | |
if(i < 10) | |
index++; | |
else | |
index--; | |
index = (index + arr.Length)%arr.Length; | |
Console.WriteLine("index: " + index + ", " + arr[index] + " (" + (i < 10 ? "forward" : "backward") + ")"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This line is useful when you have a gallery of images (for example) with navigation arrows that you want to infinitely scroll through:
index = (index + arr.Length)%arr.Length;
This saves you unnecessary if branching and bounds checks...
Output:
index: 1, 2 (forward)
index: 2, 3 (forward)
index: 3, 4 (forward)
index: 0, 1 (forward)
index: 1, 2 (forward)
index: 2, 3 (forward)
index: 3, 4 (forward)
index: 0, 1 (forward)
index: 1, 2 (forward)
index: 2, 3 (forward)
index: 1, 2 (backward)
index: 0, 1 (backward)
index: 3, 4 (backward)
index: 2, 3 (backward)
index: 1, 2 (backward)
index: 0, 1 (backward)
index: 3, 4 (backward)
index: 2, 3 (backward)
index: 1, 2 (backward)
index: 0, 1 (backward)