Skip to content

Instantly share code, notes, and snippets.

@ErisianArchitect
Created July 12, 2012 23:21
Show Gist options
  • Save ErisianArchitect/3101785 to your computer and use it in GitHub Desktop.
Save ErisianArchitect/3101785 to your computer and use it in GitHub Desktop.
Array Helper class
public sealed class ArrayHelper
{
internal static Random rand = new Random();
public static void Swap<T>(ref T[] source, int sourceIndex, int swapIndex)
{
if (source != null && sourceIndex >= 0 && sourceIndex < source.Length && swapIndex >= 0 && swapIndex < source.Length && swapIndex != sourceIndex)
{
T tmp = source[sourceIndex];
source[sourceIndex] = source[swapIndex];
source[swapIndex] = tmp;
}
}
//Takes the item from the source index and pushes inserts it into the the array somewhere else
//pushing all the other items towards the empty spot
public static void InsertSwap<T>(ref T[] source, int sourceIndex, int insertIndex)
{
if (source != null && sourceIndex >= 0 && sourceIndex < source.Length && insertIndex >= 0 && insertIndex < source.Length && insertIndex != sourceIndex)
{
int cpySize = 0;
T tmp;
if (sourceIndex > insertIndex)
{
cpySize = sourceIndex - insertIndex;
tmp = source[sourceIndex];
Array.Copy(source, insertIndex, source, insertIndex + 1, cpySize);
source[insertIndex] = tmp;
}
else
{
cpySize = insertIndex - sourceIndex;
tmp = source[sourceIndex];
Array.Copy(source, sourceIndex + 1, source, sourceIndex, cpySize);
source[insertIndex] = tmp;
}
}
}
//Sorts an array of comparable objects
public static void Sort<T>(ref T[] unsorted, bool ascending) where T : IComparable
{
int left = 0, right = unsorted.Length, lowIndex, comparer = ascending ? -1 : 1;
while (left < right)
{
lowIndex = left;
for (int i = left + 1; i < right; i++)
{
if (unsorted[i].CompareTo(unsorted[lowIndex]) == comparer)
lowIndex = i;
}
ArrayHelper.InsertSwap<T>(ref unsorted, lowIndex, left);
left++;
}
}
public static void Shuffle<T>(ref T[] source)
{
Shuffle<T>(ref source, 1, rand);
}
public static void Shuffle<T>(ref T[] source, Random random)
{
Shuffle<T>(ref source, 1, random);
}
public static void Shuffle<T>(ref T[] source, int shuffleCount, Random random)
{
if (shuffleCount <= 0)
shuffleCount = 1;
else if (shuffleCount > 64)
shuffleCount = 64;
for (int shuff = 0; shuff < shuffleCount; shuff++)
{
int left = 0; int right = source.Length;
while (left < right)
{
ArrayHelper.InsertSwap<T>(ref source, random.Next(right - left) + left, left);
left++;
}
}
}
public static void Roll<T>(ref T[] source, int ammount)
{
if (ammount == 0)
return;
int amt = ammount;
bool neg = amt < 0;
if (amt < 0)
amt = -amt;
amt = amt % source.Length;
for (int i = 0; i < amt; i++)
{
if (neg)
{
ArrayHelper.InsertSwap<T>(ref source, 0, source.Length - 1);
}
else
{
ArrayHelper.InsertSwap<T>(ref source, source.Length - 1, 0);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment