Last active
February 9, 2023 15:01
-
-
Save roberocity/1682994 to your computer and use it in GitHub Desktop.
Shuffle Array
This file contains hidden or 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
// Sattolo's algorithm as an extention method of Array | |
public static T[] Shuffle<T>(this T[] array) | |
{ | |
var random_generator = new Random(DateTime.Now.Millisecond); | |
int i = array.Length-1; | |
while (i > 1) | |
{ | |
i--; | |
int j = random_generator.Next(i); | |
T tmp = array[j]; | |
array[j] = array[i]; | |
array[i] = tmp; | |
} | |
return array; | |
} | |
public static T[] Shuffle2<T>(this T[] array) | |
{ | |
return array.OrderBy(x => System.Guid.NewGuid()).ToArray(); | |
} | |
public static T[] Shuffle3<T>(this T[] array) | |
{ | |
var r = new Random(DateTime.Now.Millisecond); | |
return array.OrderBy(x => r.Next()).ToArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment