Get random elements from array in Swift

Xcode 11 • Swift 5.1 extension Collection { func choose(_ n: Int) -> ArraySlice<Element> { shuffled().prefix(n) } } Playground testing var alphabet = [“A”,”B”,”C”,”D”,”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,”Q”,”R”,”S”,”T”,”U”,”V”,”W”,”X”,”Y”,”Z”] let shuffledAlphabet = alphabet.shuffled() // “O”, “X”, “L”, “D”, “N”, “K”, “R”, “E”, “S”, “Z”, “I”, “T”, “H”, “C”, “U”, “B”, “W”, “M”, “Q”, “Y”, “V”, “A”, “G”, “P”, “F”, “J”] … Read more

Card Shuffling in C#

Use Fisher-Yates shuffle. Your C# code should look something like this: static public class FisherYates { static Random r = new Random(); // Based on Java code from wikipedia: // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle static public void Shuffle(int[] deck) { for (int n = deck.Length – 1; n > 0; –n) { int k = r.Next(n+1); int temp … Read more

Is this C implementation of Fisher-Yates shuffle correct?

First, you should extract the code for generating a random number that’s equally distributed between 0 (inclusive) and n (exclusive) to a separate function. That’s a nice task of work that you will need elsewhere, too. Second, I would not call srand inside the shuffle function but depend on the caller on initializing the random … Read more

How to randomize (shuffle) a JavaScript array?

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle. You can see a great visualization here (and the original post linked to this) function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle. while (currentIndex != 0) { // Pick a remaining element. randomIndex = Math.floor(Math.random() * currentIndex); … Read more