Reputation: 6646
How can i avoid repeating random number in this function ?
var maxImg = 15;
function hexImgName() {
var imgSRC = '';
$(".hexagon-img img").each(function (i) {
var randomImg = Math.floor(Math.random() * maxImg) + 1; //generate a random number from 0 to 10
imgSRC = 'img/hex/pic-' + randomImg + '.gif';
$(this).attr('src', imgSRC);
});
}
I have 15 images in my folder image name pic-1.gif , pic-2.gif , pic-3.gif ... pic-15.gif
I am changing img src path via jQuery img/hex/pic-' + randomImg + '.gif';
My question
I need to different src path on each images but img src path dont repeat
Thanks
Upvotes: 0
Views: 901
Reputation: 2664
You can generate an array with the required numbers, shuffle it and use it's number one after another:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var maxImg = 15;
for (var i = maxImg, a=[]; i--;) a.push(i);
shuffle(a);
function hexImgName() {
var pos = 0;
var imgSRC = '';
$(".hexagon-img img").each(function (i) {
var randomImg = a[pos++];
imgSRC = 'img/hex/pic-' + randomImg + '.gif';
$(this).attr('src', imgSRC);
});
}
You can see an updated version of your JSFiddle here - http://jsfiddle.net/LELGE/26/
Upvotes: 3
Reputation: 8246
To simply not get the same number consecutively, just do this:
var maxImg = 15;
var lastImg;
function hexImgName() {
var imgSRC = '';
$(".hexagon-img img").each(function (i) {
var randomImg = Math.floor(Math.random() * maxImg) + 1; //generate a random number from 0 to 10;
while (lastImg==randomImg) {
randomImg = Math.floor(Math.random() * maxImg) + 1; //generate a random number from 0 to 10;
}
lastImg=randomImg;
imgSRC = 'img/hex/pic-' + randomImg + '.gif';
$(this).attr('src', imgSRC);
});
}
Upvotes: 1
Reputation: 3559
Try like this:
var grabBag = [1,2,3,4,5,6,7,8,9,10];
// randomize order of elements with a sort function that randomly returns -1/0/1
grabBag.sort(function(xx,yy){ return Math.floor(Math.random() * 3) - 1; })
function getNextRandom(){
return grabBag.shift();
};
var originalLength = grabBag.length;
for(var i = 0; i < originalLength .length; i++){
console.log(getNextRandom());
}
Upvotes: 1