Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle an array the same way every time?

Calling Array#shuffle shuffles an array randomly, but I want to shuffle reproducibly – i.e., the same way every time. Is there a method for that? I want to call, for example, shuffle_with_key(123) and get the same result every time.

like image 788
Rails beginner Avatar asked Apr 13 '14 20:04

Rails beginner


People also ask

What is the most efficient way to shuffle an array?

Method 4: In this method we will select 2 indices randomly and then swap them. This process will be randomly repeated up to n/2 to n times, Where n is the length of array. Method 5: This is the one of the most efficient methods, it is the Fisher–Yates shuffle Algorithm.

How to shuffle a sequence of numbers in Python?

Shuffling a sequence of numbers have always been a useful utility, it is nothing but rearranging the elements in an array. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved. Method 1: In this method we use shuffle () method from numpy library.

What is the Fisher-Yates shuffle algorithm?

Let’s discuss a particular case. Shuffling an array of values is considered one of the oldest problems in computer science. Shuffling is possible with the Fisher-Yates shuffle algorithm for generating a random permutation of a finite sequence. That is to say, the algorithm shuffles the sequence.

How to swap 3 variables in an array without using 4th variable?

If the length of the array is even then we can easily Swap 2 Variables without using 3rd variable for every pair of contiguous elements. If the length of the array is odd then we can do the same as above, but the last 3 elements will not form a pair, So will we can easily Swap those 3 Variables without using 4th variable.


2 Answers

Array#shuffle can take a seeded Random instance.

a = [1,2,3,4]
seed = 1

a.shuffle(random: Random.new(seed))
# => [4, 1, 3, 2]

a.shuffle(random: Random.new(seed))
# => [4, 1, 3, 2]

Just replace seed = 1 with whatever random seed you want to use.

like image 152
user513951 Avatar answered Nov 15 '22 06:11

user513951


Yes there is. Look the below :

(arup~>~)$ pry --simple-prompt
>> a = [ 1, 2, 3 ]
=> [1, 2, 3]
>> a.shuffle(random: Random.new(1))
=> [1, 3, 2]
>> a.shuffle(random: Random.new(1))
=> [1, 3, 2]
>> a.shuffle(random: Random.new(1))
=> [1, 3, 2]
>> a.shuffle(random: Random.new(1))
=> [1, 3, 2]
>> a.shuffle(random: Random.new(1))
=> [1, 3, 2]
>> a.shuffle(random: Random.new(2))
=> [3, 2, 1]
>> a.shuffle(random: Random.new(2))
=> [3, 2, 1]
>> a.shuffle(random: Random.new(2))
=> [3, 2, 1]

Read the documentation of shuffle(random: rng) → new_ary

The optional rng argument will be used as the random number generator.

You method would look like :-

def shuffle_with_key(ary,rng)
  ary.shuffle(random: Random.new(rng))
end
like image 27
Arup Rakshit Avatar answered Nov 15 '22 08:11

Arup Rakshit