Skip to content

Instantly share code, notes, and snippets.

@uchida
Last active Sep 28, 2015
Embed
What would you like to do?
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