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.

2
  • 2
    Duplicate stackoverflow.com/questions/1816378/… Commented Sep 29, 2010 at 4:47
  • 1
    Your hypotetic function dropped 2 elements from array. Even shuffle can't do that, gg! Commented Sep 29, 2010 at 5:00

5 Answers 5

13

Use the shuffle method ...

irb(main):001:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]
Sign up to request clarification or add additional context in comments.

Comments

8

the shuffle command returns a randomized version of an array

eg:

[1,2,3].shuffle => [2,3,1]

1 Comment

and if you want to randomize in place, you can just write @number.shuffle!
1
[1,2,3,4,5,6,7,8,9].sort_by {rand}[0,9]  
=> [5, 7, 3, 8, 9, 4, 2, 1, 6]

Comments

-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

1 Comment

At least, he is the only one here, who gave a working solution without built-in functions.
-2
loop n times
   i = random array index
   j = random array index
   swap elements i and j
end

7 Comments

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.
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: What are you talking about? Why does it matter if n is even or odd?
@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.
@gaearon: There was no requirement to ensure that all elements get swapped at least once.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.