I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:
for(var l=0; l<5; l++)
simple and cryptographically secure with randojs:
console.log(randoSequence(4))
<script src="https://randojs.com/2.0.0.js"></script>
Generate a range of numbers:
var numbers = [1, 2, 3, 4];
And then shuffle it:
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var random = shuffle(numbers);
If the range of random numbers is not very large you can use this:
var exists = [],
randomNumber,
max = 5;
for(var l = 0; l < max; l++) {
do {
randomNumber = Math.floor(Math.random() * max);
} while (exists[randomNumber]);
exists[randomNumber] = true;
alert(randomNumber)
}
DEMO
var randomNumber = [];
for (var i = 0; i < 16; i++) {
var number = Math.floor(Math.random() * 4);
var genNumber = randomNumber.indexOf(number);
if (genNumber === -1) {
randomNumber.push(number);
}
}
HTML
<p id="array_number" style="font-size: 25px; text-align: center;"></p>
JS
var min = 1;
var max = 90;
var stop = 6; //Number of numbers to extract
var numbers = [];
for (let i = 0; i < stop; i++) {
var n = Math.floor(Math.random() * max) + min;
var check = numbers.includes(n);
if(check === false) {
numbers.push(n);
} else {
while(check === true){
n = Math.floor(Math.random() * max) + min;
check = numbers.includes(n);
if(check === false){
numbers.push(n);
}
}
}
}
sort();
//Sort the array in ascending order
function sort() {
numbers.sort(function(a, b){return a-b});
document.getElementById("array_number").innerHTML = numbers.join(" - ");
}
DEMO
The answers given by Adil and Minko have a major problem (although Minko at least constrained it to a small set of numbers): They go over the same numbers over and over again.
In that sense, a better method would be to create the array containing the possible values, shuffle it and then just pop elements off of it. This will require the complexity of shuffling the array, but it will get rid of the problem mentioned above.
var elements = [1, 2, 3, 4];
elements.shuffle(); // not a standard Javascript function, needs to be implemented
while( elements.length > 0 ) {
console.log( elements.pop() );
}