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); } }
erm. this is interesting... just wrote this which will try to generate a unique number from a set until it runs out of such. eg, if params are 10, 20 - it will produce a single number between 10 and 20 (inclusive of 10 and 20) and give up after 11 iterations. var $rnd = { used: [], unique: function(min, max) { var unique = false, expired = false, cap = max - min + 1, done = 0; if (cap < 0) return; while(!unique) { var randomNo = min + Math.floor(cap * Math.random()); if (!this.used[randomNo]) { this.used[randomNo] = true; unique = true; } else { done++; } if (done > cap) unique = expired = true; } return (expired) ? null : randomNo; } }; imaginaryButton.onclick = function() { // important, function will retrun null if it can't find a unique number anymore (after 11 clicks) var foo = $rnd.unique(10, 20), bar = (foo === null) ? "sorry all numbers run out!" : foo; alert(bar); }; Code (javascript):
hi, try below code: var random2 = []; function test(random2, Q) { var Q = Q || 100; var random = Math.floor(Q * Math.random()); if (random2.toString().indexOf(random+' ') == -1) { random2.push(random+' '); //alert('Your unique message here... with random number: '+random); } return random2; } //call test function as many times as You want for (var i=1; i<100; i++) { random2 = test(random2); } //document.write(random2.join(' ; ')); //Alternatively You can assign onclick event to Your button instead of using for loop statement //but then remeber to uncomment alert message call inside test function and //of course please comment for loop statement <a href="#" onclick="javascript:random2 = test(random2);">give me unique message</a> Code (markup):
Do you not want the number to be repeated at all (while possible)? or do you not want the number to be repeated twice in a row?