6

Possible Duplicate:
Generate 8 unique random numbers between 1 and 100
Generate unique number within range (0 - X), keeping a history to prevent duplicates

I need loop that will run 80 times and generate random number between 0-79 but it will not repeat number that has been generated already.
How can I do that?

Community
  • 1
  • 1
Skizo
  • 521
  • 2
  • 8
  • 14
  • 3
    Put all numbers in an array. Shuffle. Take first. Remove first. Relevant questions: http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range, http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array, http://stackoverflow.com/questions/2380019/generate-8-unique-random-numbers-between-1-and-100 – Felix Kling Dec 16 '12 at 14:44
  • @FelixKling that doesn't solve the problem of generating uniques to populate the array with in the first place. – Asad Saeeduddin Dec 16 '12 at 14:46
  • @Asad: Has been answered before though. And since they need 80 numbers and have exactly 80 numbers (0-79), there is no need to generate them. All that is left to do is to put 0-80 in an array and shuffle that array. – Felix Kling Dec 16 '12 at 14:47
  • @FelixKling Yeah I can't believe I missed that. – Asad Saeeduddin Dec 16 '12 at 14:52

1 Answers1

16
  for (var i = 0, ar = []; i < 80; i++) {
    ar[i] = i;
  }

  // randomize the array
  ar.sort(function () {
      return Math.random() - 0.5;
  });

// You have array ar with numbers 0 to 79 randomized. Verify
console.log(ar);

// take out elements like this
ar.pop()

closure
  • 7,412
  • 1
  • 23
  • 23
  • why ` - 0.5` ? Just did a test and it didn't seem to make a difference. But I just wanted to make sure I wasn't missing anything. – Michael S Dec 11 '15 at 16:48
  • nevermind. I found the explanation here: https://teamtreehouse.com/community/return-mathrandom05 – Michael S Dec 11 '15 at 16:52