0

I have multiple cases that are under Math.random but sometimes they repeat. It looks a little unprofessional. Is there a way to always go to another random case?

putvande
  • 15,068
  • 3
  • 34
  • 50
  • 1
    random numbers can repeat.. what number range are you looking at – gezzuzz Jul 27 '13 at 22:22
  • Define "cases". Use-cases? Switch-case? `Math.random` is not the best random/pseudo-random generator out there, so if you need more randomness, you're going to have another way to implement it. – BLaZuRE Jul 27 '13 at 22:23
  • possible duplicate of [Generating unique random numbers (integers) between 0 and 'x'](http://stackoverflow.com/questions/8378870/generating-unique-random-numbers-integers-between-0-and-x). Another possible duplicate: http://stackoverflow.com/questions/2380019/generate-8-unique-random-numbers-between-1-and-100, – bfavaretto Jul 27 '13 at 22:23
  • Which random numbers do you need? `INT` or `DECIMAL`, From-to? – Erman Belegu Jul 27 '13 at 22:23
  • 6
    Hint: fill array and shuffle. – Nemanja Boric Jul 27 '13 at 22:24
  • You might be more interested in a solution without `Math.Random`: create an array of integers from the range that you'd like, shuffle it and every time extract the next item. – Jeroen Vannevel Jul 27 '13 at 22:25
  • Can you rely on a server side implementation of Random() instead? Typically server side frameworks have better implementations than JS – TGH Jul 27 '13 at 22:27
  • I'm trying to load 15 different htmls in an iframe from a button outside of the iframe. – user2617514 Jul 27 '13 at 22:27
  • @BLaZuRE I'm using switch cases. – user2617514 Jul 27 '13 at 22:29
  • `Math.floor((Math.random()*15)+1);` – Erman Belegu Jul 27 '13 at 22:30
  • Define them as a named function and then call them with different parameters? Don't really know what you mean to be honest. Jsfiddle please. – Starkers Jul 27 '13 at 23:02

1 Answers1

1

Repeating what Nemanja Boric says in his comment: Fill an array and shuffle.

Here is an example: How can I shuffle an array?

    var myArray = ['1','2','3','4','5','6','7','8','9'];
    newArray = shuffle(myArray);

newArray will be something like ['3','8','1','9','6','4','5','2','7']

Community
  • 1
  • 1
Spencer
  • 1,527
  • 1
  • 10
  • 23