I have an interval [0; max] and I want to split it into a specific number of sub-intervals. For this, i wrote a function called getIntervalls(max, nbIntervals) where max is the max element in my first interval and nbIntervals is the number of expected sub-intervals.
For example:
getIntervalls(3, 2) should return [[0,1], [2,3]],
getIntervalls(6, 2) should return [[0,3], [4,6]],
getIntervalls(8, 3) should return [[0,2], [3,5], [6,8]],
getIntervalls(9, 3) should return [[0,3], [4,7], [8,9]],
Here is my function:
function getIntervalls(max, nbIntervalls) {
var size = Math.ceil(max / nbIntervalls);
var result = [];
if (size > 1) {
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result .push([inf, sup]);
}
} else {
result.push([0, max]);
}
return result;
}
console.log(JSON.stringify(getIntervalls(7, 2)));
It work properly, and shows this output:
[[0,4],[5,7]]
When I change the parameters to 7 and 3, it shows:
[[0,3],[4,7],[8,7]]
instead of
[[0,2],[3,5],[6,7]]
Would anyone can help me? Thank you in advance. An ES6 syntax will be appreciated! :)
You need to use Math.round() for take the nearest integer of the decimal number of the size of interval. Also, you need to descrease a one the max for size calculation to take account of the effective number of interval.
Here the modification of your code :
function getIntervalls(max, nbIntervalls) {
var size = Math.round((max-1) / nbIntervalls);
var result = [];
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result.push([inf, sup]);
if(inf >= max || sup >= max)break;
}
return result;
}
Note that it respect the wanted number of interval, so some case of couple of number can result
[..., [n-2,n-1], [n,n]].
Hope this helps!
You could check if i is zero for first element and if next increment is larger then max for second element. Also you can check if first element is smaller then max.
function getIntervalls(max, nInt) {
const c = Math.floor(max / nInt);
const r = [];
for (var i = 0; i <= max; i += c) {
const a = i == 0 ? i : i += 1;
const b = i + c > max ? max : i + c;
if (a < max) r.push([a, b])
}
return r;
}
console.log(JSON.stringify(getIntervalls(3, 2)));
console.log(JSON.stringify(getIntervalls(6, 2)));
console.log(JSON.stringify(getIntervalls(8, 3)));
console.log(JSON.stringify(getIntervalls(9, 3)));
console.log(JSON.stringify(getIntervalls(7, 2)));
console.log(JSON.stringify(getIntervalls(7, 3)));
You need to change the size calculation from Math.ceil() to Math.floor(), because of ceil it takes size +1 than what you need.
I have made modification to your code, here it will work.
function getIntervalls(max, nbIntervalls) {
var size = Math.floor(max / nbIntervalls);
var result = [];
if (size > 0) {
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size : max;
result .push([inf, sup]);
if (sup >= max) {
break;
}
}
} else {
result.push([0, max]);
}
return result;
}
console.log(JSON.stringify(getIntervalls(10, 5)));
Hope this helps!
For me, this is the perfect function for that.
It allows you to get the intervals between two numbers, and the last interval always goes to the max.
function getIntervals(min, max, nbIntervals) {
let size = Math.floor((max - min) / nbIntervals);
let result = [];
if (size <= 0) return [min, max];
for (let i = 0; i < nbIntervals; i++) {
let inf = min + (i * size);
let sup = ((inf + size) < max) ? inf + size : max;
if (i === (nbIntervals - 1)) {
if (sup < max) sup = max;
}
result.push([inf, sup]);
if (sup >= max) break;
}
return result;
}
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.
I have an annoying script I can't complete.
I need 32 non-repeating numbers out of a possible 0-64 number set. Every time I try to create a loop to check the new random number against all the numbers in the array I end up with nothing, or an infinite loop.
I'm stumped :(
Try this:
var keys = [], numbers = [], x, total = 0;
while(total < 32) {
x = Math.floor(Math.random() * 64);
// way faster that looping through the array to check if it exists
if(keys[x] == undefined) {
keys[x] = 1;
numbers.push(x);
total++;
}
}
console.log(numbers);
Working Demo
This code will generate a non repeating random number between 0 and whatever number you give it and will start over when it has been called the amount of the number you give it.
Give it a try:
let randomNumber = function (max) {
let min = 0, prevIndexes = [];
function exec(max2) {
max = max || max2;
let result = Math.floor(Math.random() * (max - min + 1) + min);
if (prevIndexes) {
if (prevIndexes.length - 1 === max) {
clear();
}
let foundDouble, eqPrevInn = true;
while (eqPrevInn) {
foundDouble = false;
result = Math.floor(Math.random() * (max - min + 1) + min);
for (let i = 0, l = prevIndexes.length; i < l; i++) {
if (result === prevIndexes[i]) {
foundDouble = true;
break;
}
}
if (!foundDouble) {
eqPrevInn = false;
}
}
}
prevIndexes.push(result);
console.log(prevIndexes);
return result;
}
let clear = function () {
if (prevIndexes) {
prevIndexes = [];
// console.log('prevIndexes has been cleared');
}
else {
// console.log('already clear');
}
}
return {
exec: exec,
clear: clear
}
};
let random32 = randomNumber(32/*range*/).exec;
for (let i = 0; i <= 32; i++) {
random32();
}