Skip to content

Instantly share code, notes, and snippets.

@uchida
Last active September 28, 2015 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchida/1408990 to your computer and use it in GitHub Desktop.
Save uchida/1408990 to your computer and use it in GitHub Desktop.
C# sample code for the random permutation generation of finite set
// the Fisher–Yates shuffle algorithm
// see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
using System;
using System.Collections.Generic;
using System.Linq;
namespace ShuffleTest {
class Program {
static void Main(string[] args) {
List<int> shuffled = ShuffleRange(0, 10).ToList<int>();
foreach (int item in shuffled) {
Console.Write(item);
}
Console.WriteLine();
Console.ReadLine();
}
static IEnumerable<int> ShuffleRange(int start, int count) {
int[] cards = Enumerable.Range(start, count).ToArray<int>();
Random rng = new Random();
for (int i = cards.Count() - 1; i > -1; i--) {
int j = rng.Next(i);
yield return cards[j];
cards[j] = cards[i];
}
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment