Hi I would like to get an random index in a specific range of a list. After that the index should not be returned again if I want another random index of a list.
Asked
Active
Viewed 149 times
-1
-
Can you post your attempt so far and where you are struggling? – Bibberty Feb 09 '19 at 00:38
1 Answers
0
Here is a way to generate random numbers in a [min, max)
range and without repetition.
It uses a lookup object to store the values returned so far for each range.
If no number can be returned, it returns undefined
.
const usedIndicesByRange = {};
function randomIntInRange(min, max) {
const key = `${min}-${max}`;
if (!(key in usedIndicesByRange)) {
usedIndicesByRange[key] = [];
}
if (usedIndicesByRange[key].length === max - min) {
return undefined;
}
const getIdx = () => Math.floor(Math.random() * (max - min) + min);
let idx = getIdx();
while (usedIndicesByRange[key].includes(idx)) {
idx = getIdx();
}
usedIndicesByRange[key].push(idx);
return idx;
}
console.log([...Array(12)].map(() => randomIntInRange(0, 10)));

jo_va
- 13,504
- 3
- 23
- 47