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

Maximal Length of List to Shuffle with Python random.shuffle?

TL;DR: It “breaks” on lists with over 2080 elements, but don’t worry too much 🙂 Complete answer: First of all, notice that “shuffling” a list can be understood (conceptually) as generating all possible permutations of the elements of the lists, and picking one of these permutations at random. Then, you must remember that all self-contained … Read more

Better way to shuffle two related lists

Given the relationship demonstrated in the question, I’m going to assume the lists are the same length and that list1[i] corresponds to list2[i] for any index i. With that assumption in place, shuffling the lists is as simple as shuffling the indices: from random import shuffle # Given list1 and list2 list1_shuf = [] list2_shuf … Read more

Random order of rows Matlab

To shuffle the rows of a matrix, you can use RANDPERM shuffledArray = orderedArray(randperm(size(orderedArray,1)),:); randperm will generate a list of N random values and sort them, returning the second output of sort as result.