C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: This is true because it performs all the operations together, rather than one after another.
Fisher-Yates ShuffleInfo: The method here uses the KeyValuePair<T, V> data structure that is included in System.Collections.Generic.
Then: It allocates another array containing the string[] elements and pairs them with a random number. Finally, it sorts.
KeyValuePairImportant: We randomize the entire array all at once, which will result in consistently random results.
C# program that uses random shuffle algorithm
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Random _random = new Random();
static string[] RandomizeStrings(string[] arr)
{
List<KeyValuePair<int, string>> list =
new List<KeyValuePair<int, string>>();
// Add all strings from array.
// ... Add new random int each time.
foreach (string s in arr)
{
list.Add(new KeyValuePair<int, string>(_random.Next(), s));
}
// Sort the list by the random number.
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array.
string[] result = new string[arr.Length];
// Copy values to array.
int index = 0;
foreach (KeyValuePair<int, string> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return copied array.
return result;
}
static void Main()
{
string[] arr = new string[]
{
"cat",
"animal",
"abacus",
"framework"
};
string[] shuffle = RandomizeStrings(arr);
foreach (string s in shuffle)
{
Console.WriteLine(s);
}
}
}
Output
abacus
framework
cat
animal
Info: Wikipedia notes that this approach is sometimes faster in high-level languages. It is unlikely to be faster in the C# language.
Fisher-Yates shuffle: Wikipedia