Image

Non-repeating random array


I wrote a script for a client's site to display a set of images randomly - without repeating an image.



I found a useful "if it exists in array" object here (and other useful method-objects):

http://www.svendtofte.com/code/usefull_prototypes/








<script src="prototypes.js"></script>
<script>
var RandStore = new Array();
var HomeImage = new Array(4);

HomeImage[0] = "image0.gif";
HomeImage[1] = "image1.gif";
HomeImage[2] = "image2.gif";
HomeImage[3] = "image3.gif";

document.write("<hr>HomeImage length: " + HomeImage.length +" RandStore length: " + RandStore.length);
document.write("<hr>");


while (RandStore.length != HomeImage.length)
	{
	var index = Math.floor(Math.random() * HomeImage.length);
	document.write("<p>HomeImage length: " + HomeImage.length +" RandStore length: " + RandStore.length + " index: " + index);

		if (RandStore.exists(index) == false)
			{
			RandStore[RandStore.length] = index;
			document.write(" ["+index+"] ");
			}

		if (RandStore.length >= HomeImage.length) 
			{ 
			document.write("<hr>HomeImage length: " + HomeImage.length +" RandStore length: " + RandStore.length); 
			break; 
			}

	} 

</script>






I know the while condition is messed up. It seems as if the length of the array RandStore does not update for the comparison. Thats why there is a nested escape. I want the loop to continue until all the values in HomeImage are used.





Here's a sample output. The number in the bracket indicates the index being stored/used.
    HomeImage length: 4 RandStore length: 0



    HomeImage length: 4 RandStore length: 0 index: 0 [0]



    HomeImage length: 4 RandStore length: 1 index: 0



    HomeImage length: 4 RandStore length: 1 index: 2 [2]



    HomeImage length: 4 RandStore length: 2 index: 3 [3]



    HomeImage length: 4 RandStore length: 3 index: 0



    HomeImage length: 4 RandStore length: 3 index: 1 [1]

    HomeImage length: 4 RandStore length: 4

You could use this script to simulate dealing cards from a single deck.