views:

89

answers:

4

I've been working on an MPD front end in Ruby, with the ability to play a random album.

album = all[(rand*all.length).floor]

Where all is an array of the names of all albums in the library, chooses the album to play.

This works, however, I find it plays some albums more than others, and sometimes very obviously (I've seen it play the same album twice in a row, more than once, my library has a few hundred albums, so this should statistically be very unlikely to happen), and on the other end, a lot of albums never get played.

Is there any way that I can get a more random number? Is there a gem that implements a better random number algorithm? Do I need to change the seed?

+2  A: 

I don't know if this will improve the results or not, but you can do rand(all.length) to get an integer directly.

AShelly
+2  A: 

Interestingly, lots of folks think the random shuffle of the IPod Shuffle isn't random either. So this puts you in good company. :-)

http://www.npr.org/templates/story/story.php?storyId=89408926&ft=1&f=1006

http://www.cnet.com.au/itunes-just-how-random-is-random-339274094.htm?omnRef=NULL

A main point of the above articles is human's sense of what is random is flawed. You probably do have a random selection.

But you may want to implement a similar "random but no repeats" feature as the IPod Shuffle has. Or "random but biased towards favorites."

Atlas1j
I second the flawed perception comment. Usually, when people complain about things being insufficiently random, what they actually want are things to be *less* random.
Peter Ruderman
+8  A: 

Instead of doing a new random selection every time, shuffle the list once and then just take albums off that shuffled queue until you feel like resetting.

queue = albums.sort_by{rand}
while next = queue.pop
   play next
end
glenn mcdonald
Hear, hear, Glenn's got it. This is why "shuffle" mode is called "shuffle" and not "random"--because the program "shuffles" the albums like a deck of cards and then draws the next one off the top each time.
Jordan
+1  A: 

What you want is Normally Distributed Random Numbers

You should also check RandomR

Yoann Le Touche