0

I have a 3x4 table of images that when the page loads all the separate images load in order to make "one image" (the images are in pieces to create somewhat of a puzzle). I have a button called automate that when click will randomize the images. What I need is a function to "check" to see if a number is already used (hopefully the code helps to make sense of this).

JS to randomize images:

function auto(){
    for (i = 0; i <= 12; i++){ 
    r=Math.floor(Math.random()*12);
    alert(r)   // Just shows where I'm at for figuring it out
    document.images[i].src="pic"+r+".gif"
}

My images are called "pic0 , pic1" etc. So the randomize number 0-12 will randomize the image source.

What I need now is a function that will step through the image 0-11 and check to see if a number has been used already to avoid duplicating the picture. This is what I have so far for that function but am stuck now.

JS for Check:

for (i=0; i < 12; i++){
check[i]=0;
}

if ( check[r] === 0)
{
    document.images[i].src = "pic" + r + ".gif";
    check[r] = 1;
}
else {
    while (check[r] ===0){
        r= (r+1) % 12;
        document.images[i].src = "pic" + r + ".gif";
        check[r] = 1;
    }
swam
  • 293
  • 6
  • 19

2 Answers2

2

What you want is a scramble function.

scramble = function(x) {
   var y = [];
   while(x.length > 0) y.push(x.splice(Math.floor(Math.random() * x.length), 1)[0]);
   return y;
}
scramble([1,2,3,4,5,6])
// [2, 4, 3, 5, 1, 6]

In the above code, we keep picking a random index from x and then removing it and appending it to the array y. In this way, x will eventually be empty and y will be a scrambled version of x.

Robert Krzyzanowski
  • 9,294
  • 28
  • 24
  • Thats pretty slick, the only thing i might suggest is to recurse while x === y, seeing as it would not be much of a "puzzle" otherwise. – Victory Mar 30 '14 at 21:31
1

You don't need to check to see if the number has been used. Instead, populate an array w/ the numbers 1 - n and shuffle them:

// using the suffle function here:
// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

var imgIndices = [];
for ( i=0; i < 12; i++ )
    imgIndices.push( i );
imgIndices = shuffle( imgIndices );

for ( var imgNum=0; imgNum < imgIndices.length; imgNum++ )
    picName="pic"+imgIndices[ imgNum ]+".gif"
Montagist
  • 394
  • 2
  • 8