Skip to content

Instantly share code, notes, and snippets.

@NovemberDev
Created March 13, 2022 11:30
Show Gist options
  • Save NovemberDev/876f249d240c199fb270a79de35b16e3 to your computer and use it in GitHub Desktop.
Save NovemberDev/876f249d240c199fb270a79de35b16e3 to your computer and use it in GitHub Desktop.
Infinitely loops an array in both directions while respecting the array bounds
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") + ")");
}
}
}
@NovemberDev
Copy link
Author

NovemberDev commented Mar 13, 2022

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment