0

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]

  • All unique
  • Random
  • Highest number is in the highest number of the index (6)

This one is not: [3, 16, 4, 22, 19039, 555, 0]

3
  • 1
    Can you please count elements in your "right" array and tell us the result? Commented Jan 12, 2021 at 18:22
  • simply you are asking for an array from 1 to array length Commented Jan 12, 2021 at 18:31
  • @MUHAMMADILYAS yes but numbers need to be spread in random order as symlink's answer. Commented Jan 12, 2021 at 18:36

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0
  • 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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.