I have an array @number = [1,2,3,4,5,6,7,8,9]
Now, I want to randomize the array content... something like eg: [5,3,2,6,7,1,8]
Please guide me how to proceed with it.
5 Answers
the shuffle command returns a randomized version of an array
eg:
[1,2,3].shuffle => [2,3,1]
1 Comment
Peter
and if you want to randomize in place, you can just write
@number.shuffle!If you are using old version of ruby... this will work
def randomize(array)
b = []
array.length.downto(1) { |n|
b.push array.delete_at(rand(n))
}
b
end
a = [1,2,3,4,5] b=randomize(a) print b
1 Comment
Nakilon
At least, he is the only one here, who gave a working solution without built-in functions.
loop n times
i = random array index
j = random array index
swap elements i and j
end
7 Comments
Dan Abramov
Random is not guaranteed to give properly distributed results. Therefore, swapping elements with two random indexes might give you array with blocks of unchanged sequences in the middle. You should increment i from 0 to n and take random j to ensure all elements get swapped at least once.
Nakilon
Awful. Even and odd
n gives two different sets of permutations. It's so sad, but still some teachers teach students of this method... Never do that!RyanHennig
@Nakilon: What are you talking about? Why does it matter if n is even or odd?
Nakilon
@RyanHennig. 1. If you give me original
array and n, I should tell you, what half of permutations' set you can't get, and what you can. With [1,2,3,4,5] and n%2 == 1 you'll never get [5,4,3,2,1]. 2. Also, in ideal random suffled array statistically the 1 element is in its original (where it would be in oredered array) place. Your shuffling of array with 1mln elements will take at least 7mln swappings to make array with 2 element on their original places.RyanHennig
@gaearon: There was no requirement to ensure that all elements get swapped at least once.
|
shufflecan't do that, gg!