DaffyDuck
DaffyDuck

Reputation: 192

Array with random unique integer numbers (0 to array.length - 1)

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

Answers (2)

symlink
symlink

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

DaffyDuck
DaffyDuck

Reputation: 192

  • In my solution we create an array of numbers in order [1, 2, 3] call arrayOfNumbers
  • We then create an empty array call randomArray
  • We forEach loop through the array we created in first step
  • We generate a random number base on the length of the array and decreasing it throughout the forEach loop
  • We then push a random number from the arrayOfNumbers to randomArray
  • At the same time (loop) after pushing a random number from arrayOfNumbers we use array methods splice to remove it from arrayOfNumbers (so we can't longer use it)
  • We short the length by one so we can only generate random number in the length of the arrayOfNumbers array. So next time we call arrayOfNumbers[random] we'll have a unique number from this array.

   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

Related Questions