Kyle
Kyle

Reputation: 1

random image with Javascript without repeating

Have been searching with Google got loads of result but not that I can successfully implement.

I use these code from javascriptkit to display a random image from an array.

<script language="JavaScript">
<!--
function random_imglink(){
var myimages=new Array()

myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"

var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1

document.write('<img src="'+myimages[ry]+'" border=0>')
}

random_imglink()
//-->
</script>

The script works very well but the images repeat itself sometimes (e.g. img6.gif -> img4.gif -> img4.gif), would like to have the images display without duplicate with the previous one.

I'm not very familiar with javascript as well as programming and this is my first time to play around with such, so any help is appreciated.

Upvotes: 0

Views: 1458

Answers (3)

Anonymous0day
Anonymous0day

Reputation: 3042

var intervalID;
var showed = {};
var loopCount = 0;

function random_imglink(){
    var myimages=new Array()

    myimages[1]="image1.gif"
    myimages[2]="image2.gif"
    myimages[3]="image3.gif"
    myimages[4]="image4.gif"
    myimages[5]="image5.gif"
    myimages[6]="image6.gif"

    var ry=Math.floor(Math.random()*myimages.length);
    
    if (ry===0) ry=1;
  
      var src = myimages[ry]
      document.body.innerHTML+=('<br>' +  Object.keys(showed).length + '/' +  myimages.length);
  
      // if all images showed 
      if( Object.keys(showed).length === myimages.length - 1 ){
        //                                              |___|
        //                                                ^
        //                                                |
        // this is what i modified -----------------------+
        
        
        
        //we reset the showed cache
        showed = {};
        
        // we increment the loopCount
        loopCount = loopCount + 1;
        if(loopCount === 3 ){
          
          clearInterval( intervalID );
          return;
        }
        document.body.innerHTML+=('<hr>incremting loopCount<hr>');
        
      }
  
      // if this src have been showed we random_imglink;
      if( showed[src] ) return random_imglink();
      
      document.body.innerHTML+=('<br>img src="'+myimages[ry]+'" border=0>');
      
      
      //we store the showed img
      showed[src] = true;
}
document.body.innerHTML+=('we start : <br>');

intervalID = setInterval( random_imglink , 500)
    


I dont know about you constraints, but if you own the code and you can modify it like you want / need, and once you understand that the way above is not the more optimized, maybe you should consider this version below !

var id;
var i = 0;
var loopCount = 0;

var myimages=[];

// we want a clone array of your myimages[]
// because we want modify it, and keep safe the original.
// it will be copied later
var clonedImages ; 

myimages.push("image1.gif");
myimages.push("image2.gif");
myimages.push("image3.gif");
myimages.push("image4.gif");
myimages.push("image5.gif");
myimages.push("image6.gif");
//       ^
//       |
// Don't have to worry about images index
// Just push in the array in the order you need.


function ran_link(){
  
  // if we have no clone or clone is empty
  // we create it
  if(! clonedImages || ! clonedImages.length ){
    
    
    if(loopCount >= 3) {
      clearInterval(id);
      return;
    }
    
    // we create a clone of myImages
    clonedImages = myimages.slice(0 , myimages.length);
    loopCount= loopCount + 1;
    
    
    document.body.innerHTML+=('<br> loop : ' + loopCount);
    i=0;
  }
  
  // We work here only with the existant element 
  //                                        |
  //                                        V
  var ry =Math.floor(Math.random() * clonedImages.length);
  
  // we extract the element from the array
  // so the array.length will be -1
  var currentImage = clonedImages.splice(ry,1);
  
  // currentImage is an array of 1 element
  // we get the value at index 0
  var currentImageURL = currentImage[0];
  
  document.body.innerHTML+=('<br>' + (i++) + ' : ' + currentImageURL  + ' <==> ' + ry);
  return cur;
  
}


id = setInterval(ran_link , 500);

Upvotes: 0

Yuriy Yakym
Yuriy Yakym

Reputation: 3931

You can create an array where you can store ids that you've already used. And then you need to find random id which is not in this array.

Here you have example code:

var usedIds = [];
...

var ry = 0;
if(userIds.length != myimages.length) { 
    // If we haven't used all the images
    do {
        ry = Math.floor(Math.random()*myimages.length);
    } while (usedIds.indexOf(ry) > -1);

    // here we have new randomized and unique image id
    usedIds.push(ry);
    // do something with new id
} else {
    // we have already used all the images
}

Upvotes: 0

theCJCsoccer
theCJCsoccer

Reputation: 621

A general answer: I think the way the random function works makes it so you can't skip repeating images unless you remove the image that you used from the array. So an idea could be to make your array a global variable outside of the function and remove the image that you already used. And then in your main function, if the array is of size zero after a removal, you can reload the array with your original set of images. Just an idea, try it out if your having trouble :)

Upvotes: 2

Related Questions