Related
I am trying to choose random unique numbers everytime when I click button. For this my function is:
const chooseNumber = () => {
var r = Math.floor(Math.random() * 75) + 1;
console.log(r)
while(selectedNumbers.indexOf(r) === -1) {
selectedNumbers.push(r);
}
console.log(selectedNumbers);
};
But the problem is if the random number is already on my list, I need to click the button again to generate new number and it goes until it find the number which is not on the list. But I want to generate number which is not on the list directly so I dont need to click the button everytime. Thanks for you helps.
You are in a right track, except the while loop should be for random number generator, not pushing number into an array:
const selectedNumbers = [];
const chooseNumber = () => {
let r;
do
{
r = Math.floor(Math.random() * 75) + 1;
}
while(selectedNumbers.indexOf(r) > -1)
selectedNumbers.push(r);
console.log(r, "["+selectedNumbers+"]");
};
<button onclick="chooseNumber()">Generate</button>
Note, that this might eventually lead to a freeze, since there is no fail safe check if array is full, so to battle that we should also check length of the array:
const selectedNumbers = [];
const maxNumber = 75;
const chooseNumber = () => {
let r;
do
{
r = ~~(Math.random() * maxNumber) + 1;
}
while(selectedNumbers.indexOf(r) > -1 && selectedNumbers.length < maxNumber)
if (selectedNumbers.length < maxNumber)
selectedNumbers.push(r);
else
console.log("array is full");
console.log(r, "["+selectedNumbers+"]");
};
for(let i = 0; i < 76; i++)
{
chooseNumber();
}
<button onclick="chooseNumber()">Generate</button>
Don't rely on a loop to generate a unique (unseen) integer in a limited range.
First, once all of the values in the range have been exhausted there will be no possibilities left, so you'll be left in an endless loop on the next invocation.
Second, it's wasteful of the processor because you are generating useless values on each invocation.
Instead, generate all of the values in range in advance (once), then shuffle them and get the last one from the array on each invocation (and throw an error when none remain):
/**
* Durstenfeld shuffle
*
* - https://stackoverflow.com/a/12646864/438273
* - https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*/
function shuffleArray (array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
/** Get shuffled array of all integers in range */
function generateShuffledIntegerArray (min, max) {
const arr = [];
for (let i = min; i <= max; i += 1) arr.push(i);
shuffleArray(arr);
return arr;
}
const getUniqueInt = (() => {
const numbers = generateShuffledIntegerArray(1, 75);
return () => {
const n = numbers.pop();
if (typeof n === 'number') return n;
throw new Error('No unique numbers remaining');
};
})();
// Will log 75 integers, then throw on the 76th invocation:
for (let i = 1; i <= 76; i += 1) {
const n = getUniqueInt();
console.log(`${i}:`, n);
}
Code in TypeScript Playground
Your while loop is unnecessary. You could use an "if" statement instead.
To avoid clicking again on your button, you can do a recursive function like:
const chooseNumber = () => {
var r = Math.floor(Math.random() * 75) + 1;
console.log(r)
if(selectedNumbers.indexOf(r) === -1) {
selectedNumbers.push(r);
console.log(selectedNumbers);
} else {
chooseNumber();
}
};
I have a javascript function that is creating the values for a dropdown on my page. I am currently incrementing by 5, (0-100).
I am trying to change this to increment by .5 instead but it keeps just returning 0-100 with no increment.
My expected output is 0,.5,1,1.5,2,2.5 ... 100.
Here is my function so far:
/**
* Generate our possible error scores
*/
function generateErrorScores() {
var min = 0,
max = 100,
multiplier = 5, // Tried .5 here
list = [];
// Loop between min and max, increment by multiplier
for (var i = min; i <= max; i++) {
if (i % multiplier === 0) {
list.push(i);
}
}
return list;
}
console.log(generateErrorScores())
Fiddle: http://jsfiddle.net/3y451jga/
I have a feeling its if (i % multiplier === 0) { causing the problem but I am not sure how to adapt it to the .5 increments.
If all you want is the list [0, 0.5, 1, 1.5, ..., 100] you could do:
/**
* Generate our possible error scores
*/
function generateErrorScores() {
const multiplier = 0.5
return [...Array((100 / multiplier) + 1)].map((x, i) => i * multiplier)
}
console.log(generateErrorScores())
I think it would be easier to just do this
for (var i = min; i <= max; i+=0.5) {
list.push(i);
}
The if (i % multiplier === 0) serves no purpose. That works if you need multipliers off a list, but in this case you need fractions.
Interestingly, your comment is correct ("increment by multiplier") but the code is not doing that. A valid solution would be something like this:
function generateErrorScores() {
var min = 0,
max = 100,
segment = .5,
list = [];
// Loop between min and max, increment by segment
for (var i = min; i <= max; i += segment) {
list.push(i);
}
return list;
}
console.log(generateErrorScores())
function generateErrorScores() {
var min = 0,
max = 100,
increment = 0.5,
list = [];
// Loop between min and max, increment by multiplier
for (var i = min; i <= max; i = i + increment) {
list.push(i);
}
return list;
}
console.log(generateErrorScores());
You can just increment the i by 0.5 and you will get your expected output, there is no need for extra check here.
for (var i = min; i <= max; i+=0.5) {
/**
* Generate our possible error scores
*/
function generateErrorScores() {
var min = 0,
max = 100,
multiplier = 0.5,
list = [];
// Loop between min and max, increment by multiplier
for (var i = min; i <= max; i += 0.5) {
list.push(i);
}
return list;
}
console.log(generateErrorScores())
This question already has answers here:
Generate unique random numbers between 1 and 100
(32 answers)
Closed 4 years ago.
This has been asked dozens of times, but somehow, after reading many answers, I'm not convinced. I'm not cleared about the best way to do it, performance and code simplicity.
Should I set the list [1.. 100] and keep picking random (it will run 10 times) from there to another array, avoiding searching for it every new random?
Should I develop and run 10 times (at least) a random function to return a 1.. 100, checking if it is not a dupe and put it into an array?
Some Javascript function that I'm missing?
Thanks
You can use a while loop to generate random numbers with Math.random() and add the numbers to a Set which contains only unique values.
var randoms = new Set();
while(randoms.size<10){
randoms.add(1 + Math.floor(Math.random() * 100));
}
console.log([...randoms.values()]);
You can also just use an Array and check if the generated random number already exists in it before pushing it to the Array.
var randoms = [];
while(randoms.length<10){
var random = Math.ceil(1 + Math.floor(Math.random() * 100));
if(randoms.indexOf(random)==-1){
randoms.push(random);
}
}
console.log(randoms);
For a more generic function, you can use this:
function generateRandoms(min, max, numOfRandoms, unique){
/*min is the smallest possible generated number*/
/*max is the largest possible generated number*/
/*numOfRandoms is the number of random numbers to generate*/
/*unique is a boolean specifying whether the generated random numbers need to be unique*/
var getRandom = function(x, y){
return Math.floor(Math.random() * (x - y + 1) + y);
}
var randoms = [];
while(randoms.length<numOfRandoms){
var random = getRandom(min, max);
if(randoms.indexOf(random)==-1||!unique){
randoms.push(random);
}
}
return randoms;
}
function generateRandoms(min, max, numOfRandoms, unique){
var getRandom = function(x, y){
return Math.floor(Math.random() * (x - y + 1) + y);
}
var randoms = [];
while(randoms.length<numOfRandoms){
var random = getRandom(min, max);
if(randoms.indexOf(random)==-1||!unique){
randoms.push(random);
}
}
return randoms;
}
console.log(generateRandoms(1, 100, 10, true));
This technique creates N1 numbers (the total range) and shuffles them, then picks the top N2 number (how many we actually want), we'll use Fisher-Yates shuffle.
const n1 = 100;
const n2 = 10;
let pool = [...Array(n1).keys()];
var result = [];
while (result.length < n2) {
let index = Math.floor(Math.random() * pool.length);
result = result.concat(pool.splice(index, 1));
}
console.log(result);
var randomArray = [];
while(randomArray.length < 10) {
var random = Math.round(Math.random() * 100);
if(randomArray.indexOf(random) === -1) {
randomArray.push(random);
}
}
console.log(randomArray);
#2 would be the most efficient.
var nums = []
while(nums.length < 10) {
var n = Math.round(Math.random()*100);
if (!nums.includes(n)) nums.push(n);
}
console.log(nums);
You could also use Set in a newer browser, which would be a little faster than manually checking for existence:
var nums = new Set();
while(nums.size < 10) {
var n = Math.round(Math.random()*100);
nums.add(n);
}
console.log([...nums.values()]);
This function adds all numbers from betweenStart to betweenEnd, randomizes them over randomRuns loops and returns a list with amount entries:
function randomNumbersBetweenXAndY(betweenStart, betweenEnd, amount, randomRuns) {
if (betweenStart === void 0) { betweenStart = 0; }
if (betweenEnd === void 0) { betweenEnd = 100; }
if (amount === void 0) { amount = 10; }
if (randomRuns === void 0) { randomRuns = 1; }
//Verify parameters
var maxPossibleCandidates = Math.abs(betweenStart - betweenEnd) + 1;
if (amount > maxPossibleCandidates) {
console.warn("You cannot get more unique numbers between " + betweenStart + " and " + betweenStart + " than " + maxPossibleCandidates + ". " + amount + " is too many!");
amount = maxPossibleCandidates;
}
//array to return
var list = [];
//fill array
for (var index = betweenStart; index <= betweenEnd; index++) {
list.push(index);
}
//Randomize
while (randomRuns--) {
for (var index = 0; index < list.length; index++) {
var randomIndex = Math.floor(Math.random() * list.length);
var tmp = list[index];
list[index] = list[randomIndex];
list[randomIndex] = tmp;
}
}
//Return data
return list.slice(0, amount);
}
//TEST
console.log(randomNumbersBetweenXAndY(1, 100, 10));
I'm working on a project for school. I need to generate an array of 15 random integers between 1 & 50. I have a function, but I would not like for the numbers to repeat. (for example, if the number 3 is located at index 0, I would not like for it to show up again in the array.) If I could get some help on not getting repeat numbers, that would be great.
Thank you for any help!
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
In the loop generate a new random number while the number is in the array. In other words only continue when the new number is not in the array already.
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
do
{
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
}while(arr.includes(arrayValue))
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
genArray();
You can make a function in which check the number if its already in array than regenrate the number else push the number in array
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * max) + min;
if(checkno(arrayValue)==true)
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
function checkno(var no)
{
for(var i=0;i<arr.length;i++)
{
if(arr[i]==no)
return false;
else
return true;
}
}
An alternate solution involves the Set object, sets only have unique elements, multiple elements of the same value are ignored.
Example of the set object implemented for this use:
var temp = new Set();
while (temp.size < 15) {
var min = 1;
var max = 50;
temp.add(Math.floor(Math.random()*(max-min+1))+min);
}
This approach uses Arrow functions, forEach and includes functions.
let LENGTH = 15;
let numbers = new Array(LENGTH).fill();
let findRandomNumber = (i) => {
let rn;
while (numbers.includes((rn = Math.floor(Math.random() * 50) + 1))) {}
numbers[i] = rn;
};
numbers.forEach((_, i) => findRandomNumber(i));
console.log(numbers.sort((a, b) => a - b));
.as-console-wrapper {
max-height: 100% !important
}
You do not need to check the resulting array and regenerate the number. It is not efficient.
Please take a look at the following snippet:
function get_N_rand(N = 15, min = 1, max = 50) { // set default values
var N_rand = [], range = [];
for (var i = min; i <= max;) range.push(i++); // make array [min..max]
while (N_rand.length < N) { // cut element from [min..max] and put it into result
var rand_idx = ~~(Math.random() * range.length);
N_rand.push(range.splice(rand_idx, 1)[0]);
}
return N_rand;
}
console.log(JSON.stringify( get_N_rand() )); // run with defaults
console.log(JSON.stringify( get_N_rand(6, 10, 80) )); // run with arbitraries
I need to get random number, but it should not be equal to the previous number. Here is my piece of the code. But it doesn't work.
function getNumber(){
var min = 0;
var max = 4;
var i;
i = Math.floor(Math.random() * (max - min)) + min;
if (i=== i) {
i = Math.floor(Math.random() * (max - min)) + min;
}
return i;
};
console.log(getNumber());
This answer presents three attempts
A simple version with a property of the function getNumber, last, which stores the last random value.
A version which uses a closure over the min and max values with raising an exception if max is smaller than min.
A version which combines the closure and the idea of keeping all random values and use it as it seems appropriate.
One
You could use a property of getNumber to store the last number and use a do ... while loop.
function getNumber() {
var min = 0,
max = 4,
random;
do {
random = Math.floor(Math.random() * (max - min)) + min;
} while (random === getNumber.last);
getNumber.last = random;
return random;
};
var i;
for (i = 0; i < 100; i++) {
console.log(getNumber());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Two
Another proposal with a closure over the interval and the last random value.
function setRandomInterval(min, max) {
var last;
if (min >= max) {
throw 'Selected interval [' + min + ', ' + max + ') does not work for random numbers.';
}
return function () {
var random;
do {
random = Math.floor(Math.random() * (max - min)) + min;
} while (random === last);
last = random;
return random;
};
}
var i,
getRandom = setRandomInterval(0, 4);
for (i = 0; i < 100; i++) {
console.log(getRandom());
}
setRandomInterval(4, 4); // throw error
.as-console-wrapper { max-height: 100% !important; top: 0; }
Three
This proposal uses the idea to minimise the call of a new random number. It works with two variables, value for the continuing same random value and count for saving the count of the same value.
The function looks first if the saved count is given and if the value is not equal with the last value. If that happens, the saved value is returned and count is decremented.
Otherwise a new random numner is generated and checked as above (first proposal). If the number is equal to the last value, the count is incremented and it goes on with generating a new random value.
As result, almost all previous generated random values are used.
function setRandomInterval(min, max) {
var last, // keeping the last random value
value, // value which is repeated selected
count = 0, // count of repeated value
getR = function () { return Math.floor(Math.random() * (max - min)) + min; };
if (min >= max) {
throw 'Selected interval [' + min + ', ' + max + ') does not work for random numbers.';
}
return function () {
var random;
if (count && value !== last) {
--count;
return last = value;
}
random = getR();
while (random === last) {
value = random;
++count;
random = getR();
}
return last = random;
};
}
var i,
getRandom = setRandomInterval(0, 4);
for (i = 0; i < 100; i++) {
console.log(getRandom());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
The following method generates a new random number in the [min, max] range and makes sure that this number differs from the previous one, without looping and without recursive calls (Math.random() is called only once):
If a previous number exists, decrease max by one
Generate a new random number in the range
If the new number is equal to or greater than the previous one, add one
(An alternative: If the new number is equal to the previous one, set it to max + 1)
In order to keep the previous number in a closure, getNumber can be created in an IIFE:
// getNumber generates a different random number in the inclusive range [0, 4]
var getNumber = (function() {
var previous = NaN;
return function() {
var min = 0;
var max = 4 + (!isNaN(previous) ? -1 : 0);
var value = Math.floor(Math.random() * (max - min + 1)) + min;
if (value >= previous) {
value += 1;
}
previous = value;
return value;
};
})();
// Test: generate 100 numbers
for (var i = 0; i < 100; i++) {
console.log(getNumber());
}
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
The [min, max] range is made inclusive by adding 1 to max - min in the following statement:
var value = Math.floor(Math.random() * (max - min + 1)) + min;
This is not a requirement in the question but it feels more natural to me to use an inclusive range.
First of all function should compare with previous value, now We have only i variable which is compared to itself. To be sure that we not have previous value we need to do loop inside ( recursive in my solution ), because single if statement not give us sure that second random will be not the same ( exists chance on that ). Your number set is very small so chance for collision is high and it is possible that loop needs few executions.
function getNumber(prev){
var min = 0;
var max = 4;
var next;
next = Math.floor(Math.random() * (max - min)) + min;
if (next===prev) {
console.log("--run recursion. Our next is ="+next); //log only for test case
next = getNumber(prev); //recursive
}
return next;
};
//test 100 times
var num=0;
for ( var i=0; i<100; i++){
num=getNumber(num);
console.log(num);
}
As You can see in tests we never have two the same values next to each other. I also added some console.log to show how many times recursion needs to run to find next number which is different then previous one.
A general solution
Keep track of the last generated number. When generating a new number, check that it differs from the last one. If not, keep generating new numbers until it is different, then output it.
Working demo
var getNumber = (function(){
var min = 0;
var max = 4;
var last = -1;
return function(){
var current;
do{
// draw a random number from the range [min, max]
current = Math.floor(Math.random() * (max + 1 - min)) + min;
} while(current === last)
return (last = current);
}
})();
// generate a sequence of 100 numbers,
// see that they all differ from the last
for(var test = [], i = 0; i < 100; i++){
test[i] = getNumber();
}
console.log(test);
Comment about computational efficiency
As discussed in comments and other answers, a potential drawback of the approach above is that it may require several attempts at generating a random number if the generated number equals the previous. Note that the probability of needing many attempts is quite low (it follows a rapidly declining geometric distribution). For practical purposes, this is not likely to have any noticeable impact.
However, it is possible to avoid making several attempts at generating a new random number by directly drawing a random number from the set of numbers in the range [min, max] excluding the previously drawn number: This is well demonstrated in the answer by #ConnorsFan, where only one random number is generated at each function call, while randomness is still preserved.
You'll need a variable with a greater scope than the variables local to your getNumber function. Try:
var j;
function getNumber(){
var min = 0;
var max = 4;
var i = Math.floor(Math.random() * (max - min)) + min;
if (j === i) {
i = getNumber();
}
j = i;
return i;
};
Remove the previous value from the set of possible values right from the start.
function getNumber(previous) {
var numbers = [0, 1, 2, 3, 4];
if (previous !== undefined) {
numbers.splice(numbers.indexOf(previous), 1);
}
var min = 0;
var max = numbers.length;
var i;
i = Math.floor(Math.random() * (max - min)) + min;
return numbers[i];
};
//demonstration. No 2 in a row the same
var random;
for (var i = 0; i < 100; i++) {
random = getNumber(random);
console.log(random);
}
You can use an implementation of #NinaScholz pattern, where the previous value is stored as property of the calling function, substituting conditional logic to increment or decrement current return value for a loop.
If the current value is equal to the previously returned value, the current value is changed during the current function call, without using a loop or recursion, before returning the changed value.
var t = 0;
function getNumber() {
var min = 0,
max = 4,
i = Math.floor(Math.random() * (max - min)) + min;
console.log(`getNumber calls: ${++t}, i: ${i}, this.j: ${this.j}`);
if (isNaN(this.j) || this.j != i) {
this.j = i;
return this.j
} else {
if (this.j === i) {
if (i - 1 < min || i + 1 < max) {
this.j = i + 1;
return this.j
}
if (i + 1 >= max || i - 1 === min) {
this.j = i - 1;
return this.j
}
this.j = Math.random() < Math.random() ? --i : ++i;
return this.j
}
}
};
for (var len = 0; len < 100; len++) {
console.log("random number: ", getNumber());
}
This solution uses ES6 generators and avoids generating random numbers until you find one that complies with the precondition (two correlated numbers must be different).
The main idea is to have an array with the numbers and an array with indexes. You then get a random index (to comply with the precondition, the indexes' array will be the result of filtering the array of indexes with the previous selected index). The return value will be the number that correspond to the index in the numbers' array.
function* genNumber(max = 4) {// Assuming non-repeating values from 0 to max
let values = [...Array(max).keys()],
indexes = [...Array(max).keys()],
lastIndex,
validIndexes;
do {
validIndexes = indexes.filter((x) => x !== lastIndex);
lastIndex = validIndexes[Math.floor(Math.random() * validIndexes.length)];
yield values[lastIndex];
} while(true);
}
var gen = genNumber();
for(var i = 0; i < 100; i++) {
console.log(gen.next().value);
}
Here's the fiddle in case you want to check the result.
Save the previous generated random number in a array check the new number with the existing number you can prevent duplicate random number generation.
// global variables
tot_num = 10; // How many number want to generate?
minimum = 0; // Lower limit
maximum = 4; // upper limit
gen_rand_numbers = []; // Store generated random number to prevent duplicate.
/*********** **This Function check duplicate number** ****************/
function in_array(array, el) {
for (var i = 0; i < array.length; i++) {
if (array[i] == el) {
return true;
}
}
return false;
}
/*--- This Function generate Random Number ---*/
function getNumber(minimum, maximum) {
var rand = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
if (gen_rand_numbers.length <= (maximum - minimum)) {
if (!in_array(gen_rand_numbers, rand)) {
gen_rand_numbers.push(rand);
//alert(rand)
console.log(rand);
return rand;
} else {
return getNumber(minimum, maximum);
}
} else {
alert('Final Random Number: ' + gen_rand_numbers);
}
}
/*--- This Function call random number generator to get more than one random number ---*/
function how_many(tot_num) {
for (var j = 0; j < tot_num; j++) {
getNumber(minimum, maximum);
}
}
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > </script>
<input type = "button" onclick = "how_many(4)" value = "Random Number" >
You can use a augmented implementation of a linear congruential generator.
A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation.
The following function returns a seeded random number in conjunction with a min and max value:
Math.seededRandom = function(seed, min, max) {
max = max || 1;
min = min || 0;
// remove this for normal seeded randomization
seed *= Math.random() * max;
seed = (seed * 9301 + 49297) % 233280;
let rnd = seed / 233280.0;
return min + rnd * (max - min);
};
In your case, because you never want the new number to be the same as the previous, then you can pass the previously generated number as the seed.
Here is an example of this follows which generates 100 random numbers:
Math.seededRandom = function(seed, min, max) {
max = max || 1;
min = min || 0;
// remove this for normal seeded randomization
seed *= Math.random() * max;
seed = (seed * 9301 + 49297) % 233280;
let rnd = seed / 233280.0;
return min + rnd * (max - min);
};
let count = 0;
let randomNumbers = [];
let max = 10;
do {
let seed = (randomNumbers[randomNumbers.length -1] || Math.random() * max);
randomNumbers.push(Math.seededRandom(seed, 0, max));
count++;
} while (count < 100)
console.log(randomNumbers);
A fun answer, to generate numbers from 0 to 4 in one line:
console.log(Math.random().toString(5).substring(2).replace(/(.)\1+/g, '$1').split('').map(Number));
Explanation:
Math.random() //generate a random number
.toString(5) //change the number to string, use only 5 characters for it (0, 1, 2, 3, 4)
.substring(2) //get rid of '0.'
.replace(/(.)\1+/g, '$1') //remove duplicates
.split('') //change string to array
.map(Number) //cast chars into numbers
And a longer version with generator:
let Gen = function* () {
const generateString = (str) => str.concat(Math.random().toString(5).substring(2)).replace(/(.)\1+/g, '$1');
let str = generateString('');
let set = str.split('').map(Number);
while (true) {
if (set.length === 0) {
str = generateString(str).substring(str.length);
set = str.split('').map(Number);
}
yield set.pop();
}
}
let gen = Gen();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
function getNumber(){
var min = 0;
var max = 4;
var i;
i = Math.floor(Math.random() * (max - min)) + min;
while(i==getNumber.last)
i = Math.floor(Math.random() * (max - min)) + min;
getNumber.last=i;
return i;
};
console.log(getNumber());
Try this
var prev_no = -10;
function getNumber(){
var min = 0;
var max = 4;
var i;
i = Math.floor(Math.random() * (max - min)) + min;
while (i == prev_no) {
i = Math.floor(Math.random() * (max - min)) + min;
prev_no = i;
}
return i;
};
console.log(getNumber());
You can use Promise, Array.prototype.forEach(), setTimeout. Create and iterate an array having .length set to max; use setTimeout within .forEach() callback with duration set to a random value to push the index of the array to a new array for non-uniform distribution of of the indexes within the new array. Return resolved Promise from getNumber function where Promise value at .then() will be an array of .length max having random index from .forEach() callback as values without duplicate entries.
function getNumber(max) {
this.max = max;
this.keys = [];
this.arr = Array.from(Array(this.max));
this.resolver = function getRandom(resolve) {
this.arr.forEach(function each(_, index) {
setTimeout(function timeout(g) {
g.keys.push(index);
if (g.keys.length === g.max) {
resolve(g.keys)
};
}, Math.random() * Math.PI * 100, this);
}, this)
};
this.promise = new Promise(this.resolver.bind(this));
}
var pre = document.querySelector("pre");
var random1 = new getNumber(4);
random1.promise.then(function(keys) {
pre.textContent += keys.length + ":\n";
keys.forEach(function(key) {
pre.textContent += key + " ";
})
});
var random2 = new getNumber(1000);
random2.promise.then(function(keys) {
pre.textContent += "\n\n";
pre.textContent += keys.length + ":\n";
keys.forEach(function(key) {
pre.textContent += key + " ";
})
});
pre {
white-space: pre-wrap;
width: 75vw;
}
<pre></pre>
I'm surprised no one has suggested a simple solution like this:
function getRandomNum(min, max, exclude) {
if (Number.isNaN(exclude)) exclude = null;
let randomNum = null;
do {
randomNum = Math.floor(min + Math.random() * (max + 1 - min));
} while (randomNum === exclude);
return randomNum;
}
Note that "exclude" is optional. You would use it like this:
// Pick 2 unique random numbers between 1 and 10
let firstNum = getRandomNum(1, 10);
let secondNum = getRandomNum(1, 10, firstNum);
You can give it a try here:
function getRandomNum(min, max, exclude) {
if (Number.isNaN(exclude)) exclude = null;
let randomNum = null;
do {
randomNum = Math.floor(min + Math.random() * (max + 1 - min));
} while (randomNum === exclude);
return randomNum;
}
// Pick 2 unique random numbers between 1 and 10
let firstNum = getRandomNum(1, 10);
let secondNum = getRandomNum(1, 10, firstNum);
// Output the numbers
document.write(firstNum + ' and ' + secondNum);
You can't achieve this unless you you do a database query to check existence of the new number. If existing, repeat the process.
There is an architectural possibility of making unique random number is to generate two random number and combine the strings.
For example:
rand_num1 = rand(5);
rand_num2 = rand(4);
then combine rand_num1 and rand_num2 which is more like unique
Practical example:
(23456)(2345)
(23458)(1290)
(12345)(2345)
Also increase the number of digits to reduce repetition.