TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Shuffle Array

This C# example program shuffles an array with LINQ. It uses the Random type.

Shuffling an array is complex.

We can shuffle an array, randomly reordering all elements, with results that are mathematically correct. Some solutions exist but do not give high-quality random results.

Info: This article shows how to use KeyValuePair. This method is as accurate as your random number generator.

Example. First, here we see an approach to shuffling a string array that is not the classic, optimized Fisher-Yates shuffle. But this approach is mathematically random. It will not cause strange biases in your code.

And: This is true because it performs all the operations together, rather than one after another.

Fisher-Yates Shuffle: Generic Method

Class that implements array shuffling: C#

using System;
using System.Collections.Generic;
using System.Linq;

static class RandomStringArrayTool
{
    static Random _random = new Random();

    public 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;
    }
}

The method here uses the KeyValuePair<T, V> data structure that is included in System.Collections.Generic. It allocates another array containing the string[] elements and pairs them with a random number. Finally, it sorts.

KeyValuePair

This method is equally random as generating a random set of integers one-by-one. If you only randomize one element at a time, and then randomize the rest separately, you will get biases.

Note: We randomize the entire array all at once, which will result in consistently random results.

Note 2: I decided to use this approach instead of the optimized algorithms because this code wasn't on a hot path in my program.

Random numbers. It stores a Random number generator as a static field, which means you can call the RandomizeStrings method repeatedly and will get good results. More information on Random is available.

Random

Example 2. Usually, simpler methods that do not randomize all elements at once will suffice, but for more important applications, you want the very best results. Use this code in your Program.cs file. This works on a string array.

String Array

C# program that shuffles array

using System;

class Program
{
    static void Main()
    {
	string[] arr = new string[]
	{
	    "cat",
	    "animal",
	    "abacus",
	    "framework"
	};
	string[] shuffle = RandomStringArrayTool.RandomizeStrings(arr);
	foreach (string s in shuffle)
	{
	    Console.WriteLine(s);
	}
    }
}

Output

abacus
animal
framework
cat

Discussion. This article previously showed a naive method that used OrderBy in LINQ, but was not mathematically sound. The current method is mathematically sound, as noted in Wikipedia. See "Comparison with other shuffling algorithms."

orderby

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

Summary. We used a mathematically sound approach for shuffling an array. This method is not optimally fast, but for my use this wasn't important. If you need performance, use an implementation of Fisher-Yates.

Review: We saw an example of using the LINQ query syntax with a List of KeyValuePair structs.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf