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.
Asked
Active
Viewed 3,995 times
8
-
2Duplicate http://stackoverflow.com/questions/1816378/how-to-randomly-sort-scramble-an-array-in-ruby – Nakilon Sep 29 '10 at 04:47
-
1Your hypotetic function dropped 2 elements from array. Even `shuffle` can't do that, gg! – Nakilon Sep 29 '10 at 05:00
5 Answers
13
Use the shuffle
method ...
irb(main):001:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]

Dave Pirotte
- 3,806
- 21
- 14
8
the shuffle
command returns a randomized version of an array
eg:
[1,2,3].shuffle => [2,3,1]

Nikolaus Gradwohl
- 19,708
- 3
- 45
- 61
-
3and if you want to randomize in place, you can just write `@number.shuffle!` – Peter Sep 29 '10 at 05:08
-1
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

Avinasha Shastry
- 822
- 1
- 8
- 21
-
At least, he is the only one here, who gave a working solution without built-in functions. – Nakilon Sep 30 '10 at 07:12
-2
loop n times
i = random array index
j = random array index
swap elements i and j
end

RyanHennig
- 1,072
- 9
- 12
-
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. – Dan Abramov Sep 29 '10 at 04:45
-
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! – Nakilon Sep 29 '10 at 04:54
-
@Nakilon: What are you talking about? Why does it matter if n is even or odd? – RyanHennig Sep 29 '10 at 17:37
-
@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. – Nakilon Sep 30 '10 at 06:59
-
@gaearon: There was no requirement to ensure that all elements get swapped at least once. – RyanHennig Oct 15 '10 at 03:51
-
@Nakilon: 1. Of course you can. Swap 1 and 5, 2 and 4, and then 3 with itself. 2. I don't know what you mean by this point – RyanHennig Oct 15 '10 at 03:54
-