Shaz
Shaz

Reputation: 15887

Working with "Random" Arrays

For a game in the making: Using one HTML5 <audio> element and some JavaScript, I'm attempting to create a playlist that chooses a random key from an Object (which will be an Array). The Object chosen is based on the "mood" of the player's state. I then extract the source URL for the song from the Array, and if the song that's chosen did not already just play, load it, then play it. The play function is as follows (which is part of an object literal):

play: function(option) {
    if (G.audio.enabled) {
        var player = G.audio.player,
            playlist = G.audio.playlist;

        if (option && G.audio.playlist[option]) {
            G.audio.mood = option;
            var song = playlist[option][Math.floor(Math.random() * (playlist[option].length))][2];
            if (G.audio.current != song) {
                G.audio.current = song;
                player.attr("src", song);
                player[0].load();
                player[0].play();
            } else {
                G.audio.play(G.audio.mood);
            }
        } else {
            G.audio.play(G.audio.mood);
        }

        try {
            player[0].removeEventListener("ended", G.audio.play);
        } catch (e) {}
        player[0].addEventListener("ended", G.audio.play);
    }
}

So for example, if we were dealing with (and only had) the "heroic" category (which is the mood), G.audio.playlist would look like this:

heroic: [
    [
    "Song Title", 
    "Artist",
    "Source url",
    "other info"
    ],

    [
    "Song Title",
    "Artist",
    "Source url",
    "other info"
    ],

    [
    "Song Title",
    "Artist",
    "Source url",
    "other info"
    ]
];

Everything works fine, except for one thing: The second song rarely plays, whilst the the first and third are usually the ones to play upon load.

So, my question is, is there any logical reasoning on why:

playlist[option][Math.floor(Math.random() * (playlist[option].length))][2];

Would give precedence to the First ([0]) and Third key ([2]) of the Array?

Upvotes: 0

Views: 128

Answers (1)

jfriend00
jfriend00

Reputation: 708016

Try this jsfiddle and crank up numRums to as high a value as you want. I don't see a meaningful bias and it's a different result each time you run it. The percent display is the percent off of the expected avg value. I see about 0.01% variation with enough runs.

And, here's a more advanced jsfiddle that you can run as many iterations on as you want without the browser getting unhappy about the length of the running script. You can literally run 100 million iterations if you want. This is what I got from running a billion iterations on three buckets:

Number of Cycles Executed: 1,000,000,000
333,317,410    (-0.004777%)
333,330,202    (-0.000939%)
333,352,388    (+0.005716%)

Upvotes: 2

Related Questions