Random Number Generator Without Dupes in JavaScript

How to randomly generate numbers without repetition in javascript?

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);

Random number generator without dupes in Javascript?

var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];

function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}

function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}

for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}

Generating non-repeating random numbers in JS

If I understand right then you're just looking for a permutation (i.e. the numbers randomised with no repeats) of the numbers 1-10?
Maybe try generating a randomised list of those numbers, once, at the start, and then just working your way through those?

This will calculate a random permutation of the numbers in nums:

var nums = [1,2,3,4,5,6,7,8,9,10],
ranNums = [],
i = nums.length,
j = 0;

while (i--) {
j = Math.floor(Math.random() * (i+1));
ranNums.push(nums[j]);
nums.splice(j,1);
}

So, for example, if you were looking for random numbers between 1 - 20 that were also even, then you could use:

nums = [2,4,6,8,10,12,14,16,18,20];

Then just read through ranNums in order to recall the random numbers.

This runs no risk of it taking increasingly longer to find unused numbers, as you were finding in your approach.

EDIT: After reading this and running a test on jsperf, it seems like a much better way of doing this is a Fisher–Yates Shuffle:

function shuffle(array) {
var i = array.length,
j = 0,
temp;

while (i--) {

j = Math.floor(Math.random() * (i+1));

// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;

}

return array;
}

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

Basically, it's more efficient by avoiding the use of 'expensive' array operations.

BONUS EDIT: Another possibility is using generators (assuming you have support):

function* shuffle(array) {

var i = array.length;

while (i--) {
yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0];
}

}

Then to use:

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

ranNums.next().value; // first random number from array
ranNums.next().value; // second random number from array
ranNums.next().value; // etc.

where ranNums.next().value will eventually evaluate to undefined once you've run through all the elements in the shuffled array.

Overall this won't be as efficient as the Fisher–Yates Shuffle because you're still splice-ing an array. But the difference is that you're now doing that work only when you need it rather than doing it all upfront, so depending upon your use case, this might be better.

Picking Non-duplicate Random Numbers using JavaScript

Two solutions:

  1. Create a list of your numbers, then pick (and remove) 5 from them.
  2. Create a loop that keeps generating numbers until it has 5 unique ones.

Your attempt can be adapted for solution 2:

let lotto = [];
while(lotto.length < 5) {
console.log('Got', lotto.length, 'numbers!');
// Changed 69 to 5 to "force" clashes (well, make it very likely)
const num = Math.floor(Math.random() * 5) + 1;
if (!lotto.includes(num)) lotto.push(num);
}

const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);

Generate a non-repeating random number in JavaScript

You have 2 mistakes, oné is the array inside the function this cleared for each try, and then there is wrong logic ending up in an infinite loop.

const usedIndexes = [];    
function getUniqueRandomNumber(x) {
const index = Math.floor(Math.random() * (x));
if (usedIndexes.includes(index)) {
return this.getUniqueRandomNumber(x);
} else {
console.log(index);
usedIndexes.push(index);
return index;
}
}

Also, I would think about using Set, in this situation instead of the array.

const usedIndexes = new Set();    
function getUniqueRandomNumber(max, min = 0) {
const newNumber = Math.floor(Math.random() * (max - min) + min);
if (usedIndexes.has(newNumber)) {
return this.getUniqueRandomNumber(max, min);
} else {
usedIndexes.add(newNumber);
return newNumber;
}
}

I have also edited variables names to better reflect their actual use and added a minimum for a random number.

Javascript unique random number generator is not generating unique numbers

if I understand it correctly, then you need: 1. change map to forEach 2. you need to move the array where you save already generated numbers out of the forEach function 3. change the number generator loop

/* The part of what each image url has in common
⍟ var base = 'images/Image_'
*/
var base = 'images/Image_';
var suff = '.jpg';

function randomCellBG(base) {

// Reference the <table>
var T = document.getElementById('mainTable');

/* Collect all .cell into a NodeList and convert
|| it into an array
*/
var cellArray = Array.from(T.querySelectorAll('.cell'));

// initialize the array
var arr = []
// map() the array; run a function on each loop...
cellArray.forEach(function (cel, idx) {

// generate numbers 1-40 and check if they were already generated
do {
var ran = Math.ceil(Math.random() * 40)
} while (arr.indexOf(ran) > -1);
//save the newly generated unique number
arr[arr.length] = ran;

/* Concatenate base and random number to form
|| a string of a url of an image
⍟ result: "images/Image_08.jpg"
*/
var img = base + ran.toString() + suff;

/* Assign that url as the value to the
|| backgroundImage property of the .cell
|| in current iteration
*/
cel.innerHTML = "<img src='" + img + "'/>";
});
}

Generate random numbers that are in sorted into order without duplicates Javascript?

Try this:

var randomNumbers = [];  

function addNumsToArray() {
for(var i = 1; i <= 6; i++) {
number = Math.floor(Math.random() * 59 + 1);
randomNumbers.push(generateUniqNumber());
}
}

function sortArray() {
randomNumbers.sort(function(a, b){return a - b});
console.log(randomNumbers);
}

function generateUniqNumber() {
var number = Math.floor(Math.random() * 59 + 1);

if (randomNumbers.includes(number)) {
return generateUniqNumber();
}

return number;
}
addNumsToArray();
sortArray();

Generate random number within range without repeating numbers in javascript

  for (var i = 0, ar = []; i < 80; i++) {
ar[i] = i;
}

// randomize the array
ar.sort(function () {
return Math.random() - 0.5;
});

// You have array ar with numbers 0 to 79 randomized. Verify

console.log(ar);

// take out elements like this

ar.pop()

Avoid duplicates from random selection

I aggree with hoangdv but it can be event simpler

const words = ["Bus", "Plane", "Car","Dog","Cat", "House"]; function shuffle(array) {  array.sort(() => Math.random() - 0.5);  return array}
get_word = function (number) { return shuffle(words).slice(0,number)}console.log(get_word(3))console.log(get_word(3))console.log(get_word(3))


Related Topics



Leave a reply



Submit