tags:

views:

107

answers:

5

hi,

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.

thanks

A: 
loop n times
   i = random array index
   j = random array index
   swap elements i and j
end
RyanHennig
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.
gaearon
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
@Nakilon: What are you talking about? Why does it matter if n is even or odd?
RyanHennig
@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
@gaearon: There was no requirement to ensure that all elements get swapped at least once.
RyanHennig
@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
@RyanHennig, hm, sorry, I didn't think about swapping with itself.
Nakilon
+3  A: 

Use the shuffle method ...

irb(main):001:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]
Dave Pirotte
+7  A: 

the shuffle command returns a randomized version of an array

eg:

[1,2,3].shuffle => [2,3,1]
Nikolaus Gradwohl
Works on 1.8.7p249
Dave Pirotte
and if you want to randomize in place, you can just write `@number.shuffle!`
Peter
A: 

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
dude this code is a mess!
banister
At least, he is the only one here, who gave a working solution without built-in functions.
Nakilon
A: 

[1,2,3,4,5,6,7,8,9].sort_by {rand}[0,9]
=> [5, 7, 3, 8, 9, 4, 2, 1, 6]

Dhanu
good for 1.8.6 :) but now out of date!
banister