Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Created April 10, 2021 11:32
Show Gist options
  • Save abdelfattahradwan/e9c1df28297db7db4ceccd16b0adb7cc to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/e9c1df28297db7db4ceccd16b0adb7cc to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace BoardGame
{
public static class ArrayUtility
{
public static int Wrap<T>(this IList<T> list, int index)
{
if (index < 0)
{
index = Math.Abs((list.Count - Math.Abs(index)) % list.Count);
}
else
{
index %= list.Count;
}
return index;
}
public static T[] Get<T>(this IList<T> list, int start, int end)
{
bool forward = end > start;
int steps = Math.Abs(end - start);
T[] items = new T[steps + 1];
int position = 0;
if (forward)
{
for (int i = start; i <= start + steps; i++)
{
items[position] = list[list.Wrap(i)];
position++;
}
}
else
{
for (int i = start; i >= start - steps; i--)
{
items[position] = list[list.Wrap(i)];
position++;
}
}
return items;
}
public static IEnumerable<int> EnumeratorIndices<T>(this IList<T> list, int start, int end)
{
bool forward = end > start;
int steps = Math.Abs(end - start);
if (forward)
{
for (int i = start; i <= start + steps; i++)
{
yield return list.Wrap(i);
}
}
else
{
for (int i = start; i >= start - steps; i--)
{
yield return list.Wrap(i);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment