PDA

View Full Version : random message with no repeats



George Lucas
Nov 15th, 2009, 08:19 PM
im trying to display a random number, but each time a button is pressed that calls the test function, i don't want to random number to be repeated. i know i have to declare 2 variables and a while loop, but i'm stuck as to what to put in the second variable and in the while loop. any advice is appreciated

var random = Math.floor(Q * Math.random());
var random2 = ??

function test () {
document.write(random);

while (random == random2) {
document.write(random);
}
}

Philip M
Nov 15th, 2009, 10:09 PM
You are trying to generate unique random numbers. One way to do this is:-


<script type = "text/javascript">

function getNumbers() {
temp = 0;
newnumber = 0;
chosen = new Array(9);

for (i = 1; i < 10; i++) { // initialise the array with numbers 1-9 in order
chosen[i] = i;
}

for (i = 1; i < 10; i++) { // shuffle the array
newnumber = (Math.random() * 9) + 1;
newnumber = parseInt(newnumber, 10)
temp = chosen[i]
chosen[i] = chosen[newnumber];
chosen[newnumber] = temp;
}
alert (chosen);
}

getNumbers();
</script>

This will shuffle the numbers 1-9 and place them in an array "chosen".
You will also have an array of messages 1-9.
Each time the button is pressed you will want to show the message next in order, that is message[count] where count starts at 1 is incremented by one each time (and cannot exceed 9).

As this is clearly homework that is as far as I can go.



"If you can't explain it simply, you don't understand it well enough” -Albert Einstein (German born American Physicist who developed the special and general theories of relativity. Nobel Prize for Physics in 1921. 1879-1955)