How to shuffle a std::vector?

From C++11 onwards, you should prefer: #include <algorithm> #include <random> auto rng = std::default_random_engine {}; std::shuffle(std::begin(cards_), std::end(cards_), rng); Live example on Coliru Make sure to reuse the same instance of rng throughout multiple calls to std::shuffle if you intend to generate different permutations every time! Moreover, if you want your program to create different sequences … Read more

Why does random.shuffle return None?

random.shuffle() changes the x list in place. Python API methods that alter a structure in-place generally return None, not the modified data structure. >>> x = [‘foo’, ‘bar’, ‘black’, ‘sheep’] >>> random.shuffle(x) >>> x [‘black’, ‘bar’, ‘sheep’, ‘foo’] If you wanted to create a new randomly-shuffled list based on an existing one, where the existing … Read more

Is it correct to use JavaScript Array.sort() method for shuffling?

After Jon has already covered the theory, here’s an implementation: function shuffle(array) { var tmp, current, top = array.length; if(top) while(–top) { current = Math.floor(Math.random() * (top + 1)); tmp = array[current]; array[current] = array[top]; array[top] = tmp; } return array; } The algorithm is O(n), whereas sorting should be O(n log n). Depending on … Read more

Shuffling a list of objects

random.shuffle should work. Here’s an example, where the objects are lists: from random import shuffle x = [[i] for i in range(10)] shuffle(x) # print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] # of course your results will vary Note that shuffle works in place, and returns None.

How do I shuffle an array in Swift?

This answer details how to shuffle with a fast and uniform algorithm (Fisher-Yates) in Swift 4.2+ and how to add the same feature in the various previous versions of Swift. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version. Swift 4.2+ shuffle and shuffled are native … Read more