Created
March 20, 2018 10:45
-
-
Save munkbusiness/9223ccbb91835d69cc31f58551ebf8a3 to your computer and use it in GitHub Desktop.
Generic type array shuffling based on @fincha solutions
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.Collections.Generic; | |
using UnityEngine; | |
public static class EnumerableExtensions { | |
public static T[] ShuffleArray<T>(this T[] a) { | |
// Loops through array | |
for (int i = a.Length - 1; i > 0; i--) { | |
// Randomize a number between 0 and i (so that the range decreases each time) | |
int rnd = UnityEngine.Random.Range(0, i); | |
// Save the value of the current i, otherwise it'll overright when we swap the values | |
T temp = a[i]; | |
// Swap the new and old values | |
a[i] = a[rnd]; | |
a[rnd] = temp; | |
} | |
return a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All arrays automatically gets the shuffle method so you can access it on any array by simple calling anyArrayName.ShuffleArray();
Adapted from this gist by @fincha https://gist.github.com/fincha/7770c902b674973353e0