Last active
September 28, 2015 07:58
-
-
Save uchida/1408990 to your computer and use it in GitHub Desktop.
C# sample code for the random permutation generation of finite set
This file contains 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
// 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