Skip to content

Instantly share code, notes, and snippets.

@garettbass
Created October 1, 2020 18:29
Show Gist options
  • Save garettbass/970e258d724f7514c7e8b32c85e5e35f to your computer and use it in GitHub Desktop.
Save garettbass/970e258d724f7514c7e8b32c85e5e35f to your computer and use it in GitHub Desktop.
Some C# utility methods that came in handy recently
public static void Swap<T>(ref T a, ref T b) => (a,b)=(b,a);
public static void Sort<T>(ref T a, ref T b, ref T c, Comparison<T> comparison)
{
if (comparison(a, b) > 0) Swap(ref a, ref b);
if (comparison(a, c) > 0) Swap(ref a, ref c);
if (comparison(b, c) > 0) Swap(ref b, ref c);
}
public static void Sort<T>(ref T a, ref T b, ref T c, ref T d, Comparison<T> comparison)
{
if (comparison(a, b) > 0) Swap(ref a, ref b);
if (comparison(c, d) > 0) Swap(ref c, ref d);
if (comparison(a, c) > 0) Swap(ref a, ref c);
if (comparison(b, d) > 0) Swap(ref b, ref d);
if (comparison(b, c) > 0) Swap(ref b, ref c);
}
public static void Rotate<T>(ref T a, ref T b, ref T c, Func<bool> condition)
{
while (!condition()) (a,b,c)=(b,c,a);
}
public static void Rotate<T>(ref T a, ref T b, ref T c, ref T d, Func<bool> condition)
{
while (!condition()) (a,b,c,d)=(b,c,d,a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment