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++)
Appreciate all your help. But probably another way to generate random number in a given max range can be implemented as per below.
function generateRan(){
var max = 20;
var random = [];
for(var i = 0;i<max ; i++){
var temp = Math.floor(Math.random()*max);
if(random.indexOf(temp) == -1){
random.push(temp);
}
else
i--;
}
console.log(random)
}
generateRan();
Generate random numbers without any range
function getuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
}
return s4() + s4();
}
var uid = getuid();
alert(uid)
function getRanArr(lngth) {
let arr = [];
do {
let ran = Math.floor(Math.random() * lngth);
arr = arr.indexOf(ran) > -1 ? arr : arr.concat(ran);
}while (arr.length < lngth)
return arr;
}
const res = getRanArr(5);
console.log(res);
One more way to do it:
for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
console.log(random);
}
Don't know if it's even possible to make it more compact.
Tests: http://jsfiddle.net/2m3mS/1/
Here is embed demo:
$('button').click(function() {
$('.output').empty();
for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
$('.output').append('<span>' + random + '</span>');
}
}).click();
.output span {
display: inline-block;
background: #DDD;
padding: 5px;
margin: 5px;
width: 20px;
height: 20px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<button>Run</button>
So many solutions to this! Here's my code for a reuseable function that takes in 3 arguments: the number of integers wanted in the array (length) and the range that the array should be comprised of (max and min).
function generateRandomArr(length, max, min) {
const resultsArr = [];
for (let i = 0; i < length; i++) {
const newNumber = Math.floor(Math.random() * (max - min)) + min;
resultsArr.includes(newNumber) ? length += 1 : resultsArr.push(newNumber);
}
return resultsArr;
}
generateRandomArr(10, 100, 0);
// this would give a list of 10 items ranging from 0 to 100
// for example [3, 21, 56, 12, 74, 23, 2, 89, 100, 4]