SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Non-duplicating random numbers

    What is the easiest and best way to create a list of random numbers from 1 to n where there are no duplicates?

    I do not want to use javascript just php and cannot find any item here that best describes how to do this.

    Thanks
    E

  2. #2
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,830
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Try searching for "php manual rand()" and also for mt_rand()
    Last edited by John_Betong; Apr 23, 2013 at 11:03. Reason: spelling
    Learn how to be ready for The New Move to Discourse

    How to make Make Money Now with a *NEW* look

    Be sure to congratulate Patche on earning Member of the Month for July 2014

  3. #3
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,182
    Mentioned
    65 Post(s)
    Tagged
    2 Thread(s)
    Code PHP:
    $RandomNumberCount = 10; // pick 10 random numbers
    $RandomNumbers = array(); //for storing our random numbers
    for($i = 0; $i < $RandomNumberCount; $i++) { //do current operation $RandomNumberCount times
      while(true) { //loop until break
         $Rand = mt_rand(1, 60); //range of your random number to be generated
         if(!array_search($Rand, $RandomNumbers)) { //loop until random number doesnt exist in your collection
           array_push($RandomNumbers, $Rand); //save your random number
           break; //break loop trying to find unused number
         }
      }
    }
    print_r($RandomNumbers);

  4. #4
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,266
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    When you don't want duplicates, I find that the simplest method is to fill an array with the range of possible values, then shuffle the array.

    $n = 10;

    $range = range(1, $n);
    shuffle($range);
    "First make it work. Then make it better."

  5. #5
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,182
    Mentioned
    65 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by Jeff Mott View Post
    When you don't want duplicates, I find that the simplest method is to fill an array with the range of possible values, then shuffle the array.

    $n = 10;

    $range = range(1, $n);
    shuffle($range);
    And then take $range[0] to $range[$x]? I like it.


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
  •