SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2004
    Location
    revere
    Posts
    89
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    pick a set of random numbers

    I have 100 numbers (1 through 100), and want to pick 10 random numbers from this set. Normally I would do

    for (i=1; i<=10; i++) {
    myVar = random(100)+1;
    trace(myVar);
    }

    but this time I need all the random numbers to be different (thay can't repeat). How would you approach it?

    -Bartosz
    www.BGPORTFOLIO.com

  2. #2
    SitePoint Wizard bronze trophy JRMillion's Avatar
    Join Date
    Apr 2004
    Location
    Arlington VA
    Posts
    2,094
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    numsPicked=0;
    numsArray = new Array();
    while(true){
      myVar = random(100)+1;
      if(!numsArray[myVar]){
    	 trace(myVar);
    	 numsArray[myVar] = true;
    	 numsPicked++;
      }
      if(numsPicked == 10)
          break;
    }
    That should do it.

    if you were picking many numbers (meaning the amount of unpicked numbers would get small), you might want to do it a little differently. I would load an array with your numbers, then pick a random index (between 0 and array length-1) and remove that item from the array. then repeat. that way. you will always in a unique number and wont have to "retry" if you pick a dup.
    the original way would still work fine, just might take a tad longer...
    James Rice :: Ex-Mentor
    www.jamesrice.net


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •