8

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.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
nirmal
  • 1,111
  • 2
  • 10
  • 14
  • 2
    Duplicate http://stackoverflow.com/questions/1816378/how-to-randomly-sort-scramble-an-array-in-ruby – Nakilon Sep 29 '10 at 04:47
  • 1
    Your hypotetic function dropped 2 elements from array. Even `shuffle` can't do that, gg! – Nakilon Sep 29 '10 at 05:00

5 Answers5

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
1
[1,2,3,4,5,6,7,8,9].sort_by {rand}[0,9]  
=> [5, 7, 3, 8, 9, 4, 2, 1, 6]
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Dhanu
  • 69
  • 7
-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
-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
  • @RyanHennig, hm, sorry, I didn't think about swapping with itself. – Nakilon Oct 15 '10 at 09:20