Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...