1

I've looked here and elsewhere to locate some help with no success. What is happening: the same image will display more than once in a row. What I would like to happen: all images will be displayed at random before it starts over to display an image that has already displayed.

Any help would be greatly appreciated.

var total_images = 4;
var random_number = Math.floor((Math.random()*total_images));
var random_img = new Array();
random_img[0] = '<a href="/page1"><img src="/images/img1.png"></a>';
random_img[1] = '<a href="/page2"><img src="/images/img2.png"></a>';
random_img[2] = '<a href="/page2"><img src="/images/img3.png"></a>';
random_img[3] = '<a href="/page3"><img src="/images/img4.jpg"></a>';
document.write(random_img[random_number]);
BCon
  • 11
  • 1
  • 1
    [Shuffle the array](http://stackoverflow.com/q/2450954/218196) and iterate over it. When you reach the end, reshuffle. – Felix Kling Dec 09 '14 at 16:39

1 Answers1

0

I wrote a function to do just that a few days ago. Pass random_img into this and use the result. (Note, this uses lodash, so if you want to avoid that implement you own random number system).

var jumble = function(arr) {
    var len = arr.length
    var newArr = [];
    arr.forEach(function(n) {
        var rand = _.random(len-1);
        while (newArr[rand] != undefined) {
            // find next unused place in newArr
            rand = (rand + 1) % len;
        }
        newArr[rand] = n;
    });
    return newArr;
};
Simon H
  • 20,332
  • 14
  • 71
  • 128