Reputation: 192
This question is how to generate an array of all unique fixed integer numbers that the highest is equal to the length - 1 of the array.
An example of a result array: [3, 6, 4, 2, 1, 5, 0]
This one is not: [3, 16, 4, 22, 19039, 555, 0]
Upvotes: 0
Views: 84
Reputation: 12209
First populate a sequential array, then sort by returning a random result in the compareFunction.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
let arrLen = 7, resArr = []
for(let i=0; i < arrLen; i++){
resArr.push(i)
}
resArr.sort((a,b) => {
let ranBool = Math.floor(Math.random() * 2)
//returns 0 or -1, which either leaves the integers in place or sorts the second one before the first
return ranBool - 1
})
console.log(resArr)
Upvotes: 1
Reputation: 192
function randomNumbers(howMany) {
arrayOfNumbers = [];
for (let i = 0; i < howMany; i++) {
arrayOfNumbers.push(i);
};
const arr = [...arrayOfNumbers];
let length = arr.length
const randomArr = [];
arr.forEach((num, i) => {
const random = Math.floor(Math.random() * length);
randomArr.push(arrayOfNumbers[random]);
arrayOfNumbers.splice(arrayOfNumbers.indexOf(arrayOfNumbers[random]), 1);
length--
});
return randomArr;
};
console.log(randomNumbers(101));
Upvotes: 0