Not generating the same random number twice....

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark

    Not generating the same random number twice....

    Hi Yall

    I have a page where I want 5 images to appear, randomly selected from a pool
    of 50 images called 1.jpg to 50.jpg

    The following code works nicely, except for one (probably obvious)
    problem...

    $count=1;
    do {
    $random = rand(1,50);
    echo "<img src='images/$random.jpg'>";
    $count++;
    }
    while ($count<5);

    The problem is that there is nothing to stop images appearing more than
    once. I do not want this to happen...

    Any ideas on a possible solution?

    TIA

    Mark


  • Oli Filth

    #2
    Re: Not generating the same random number twice....

    Mark said the following on 13/06/2005 19:59:[color=blue]
    > Hi Yall
    >
    > I have a page where I want 5 images to appear, randomly selected from a pool
    > of 50 images called 1.jpg to 50.jpg
    >
    > The following code works nicely, except for one (probably obvious)
    > problem...
    >
    > $count=1;
    > do {
    > $random = rand(1,50);
    > echo "<img src='images/$random.jpg'>";
    > $count++;
    > }
    > while ($count<5);
    >
    > The problem is that there is nothing to stop images appearing more than
    > once. I do not want this to happen...
    >
    > Any ideas on a possible solution?
    >[/color]

    Set up an array of 50 Booleans, each initially FALSE. Every time a
    random number is chosen, check to see if the corresponding entry in the
    array is FALSE. If it is, set it to TRUE, and use that number. If it is
    already TRUE, choose another random number.


    --
    Oli

    Comment

    • Chung Leong

      #3
      Re: Not generating the same random number twice....

      1. Use range() to create an array with number 1 - 50.
      2. Use shuttle() to shuffle the numbers.
      3. Save the array in session variable.
      4. Use the proper indices, depending on which page the user's is on, to
      obtain 5 random numbers from the array.

      Comment

      • Andy Hassall

        #4
        Re: Not generating the same random number twice....

        On Mon, 13 Jun 2005 19:59:25 +0100, "Mark" <mark@ilovespam .com> wrote:
        [color=blue]
        >I have a page where I want 5 images to appear, randomly selected from a pool
        >of 50 images called 1.jpg to 50.jpg
        >
        >The following code works nicely, except for one (probably obvious)
        >problem...
        >
        >The problem is that there is nothing to stop images appearing more than
        >once. I do not want this to happen...
        >
        >Any ideas on a possible solution?[/color]


        Pick one or more random keys out of an array


        <?php print_r(array_r and(range(1,50) , 5)); ?>

        It uses the keys rather than values so you'll probably want to add one when
        making the filename.

        --
        Andy Hassall / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
        <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

        Comment

        • Justin Koivisto

          #5
          Re: Not generating the same random number twice....

          Chung Leong <chernyshevsky@ hotmail.com> wrote:
          [color=blue]
          > 1. Use range() to create an array with number 1 - 50.
          > 2. Use shuttle() to shuffle the numbers.[/color]

          That's shuffle not shuttle. ;)
          [color=blue]
          > 3. Save the array in session variable.
          > 4. Use the proper indices, depending on which page the user's is on, to
          > obtain 5 random numbers from the array.[/color]

          Why not simply use array_pop() to get through the 50 images? Then when
          the array is empty, start at step one again...

          Taking 5 random entries from a shuffled (random) array doesn't quite
          make sense to me, or am I missing something?

          --
          Justin Koivisto - justin@koivi.co m

          Comment

          • Ewoud Dronkert

            #6
            Re: Not generating the same random number twice....

            On Mon, 13 Jun 2005 19:06:29 GMT, Oli Filth wrote:[color=blue][color=green]
            >> The problem is that there is nothing to stop images appearing more
            >> than once. I do not want this to happen...[/color]
            >
            > Set up an array of 50 Booleans, each initially FALSE. Every time a
            > random number is chosen, check to see if the corresponding entry in the
            > array is FALSE. If it is, set it to TRUE, and use that number. If it is
            > already TRUE, choose another random number.[/color]

            Bad idea, generally. In this particular case, with these small numbers
            and 5 rather smaller than 50, it will probably not be problematic, but
            what if you're trying to generate the whole range in random order and
            that darn last number just won't pop up..? Easy solution:

            $a = range( 1, 50 );
            $b = shuffle( $a );
            for ( $i = 0; $i < 5; ++$i )
            echo $b[$i]."\n";

            Or written out:

            $n = 50; // range 1..n
            $k = 5; // 1 <= k <= n
            $a = range( 1, $n );
            for ( $i = 0; $i < $k; ++$i )
            {
            $j = mt_rand( $i, $n - 1 );
            echo $a[$j]."\n";
            $a[$j] = $a[$i];
            }


            --
            Firefox Web Browser - Rediscover the web - http://getffox.com/
            Thunderbird E-mail and Newsgroups - http://gettbird.com/

            Comment

            • Ewoud Dronkert

              #7
              Re: Not generating the same random number twice....

              On Mon, 13 Jun 2005 20:33:19 +0100, Andy Hassall wrote:[color=blue]
              > http://php.net/array_rand[/color]

              Ah yes.


              --
              Firefox Web Browser - Rediscover the web - http://getffox.com/
              Thunderbird E-mail and Newsgroups - http://gettbird.com/

              Comment

              • Chung Leong

                #8
                Re: Not generating the same random number twice....

                I'm just guessing that the script involves paging through a list of
                fifty images, five at a time. If that's case you'd need to have the
                same array as you go from page to page. Otherwise then, yes, as you
                said, you can just pop 5 numbers off the array.

                Another way to maintain the same randomized array across pages is to
                seed the random number engine with a fixed number, like today's date. A
                useful trick when you don't want to use session.

                Comment

                • Mark

                  #9
                  Re: Not generating the same random number twice....

                  Thanks for your replies guys (n gals?)

                  I will try them all and let you know who was "THE CHOSEN ONE"

                  Thanks again!

                  Mark



                  "Mark" <mark@ilovespam .com> wrote in message
                  news:1118689179 .0bfe721d1be719 44ad69de19a67d3 613@teranews...[color=blue]
                  > Hi Yall
                  >
                  > I have a page where I want 5 images to appear, randomly selected from a
                  > pool of 50 images called 1.jpg to 50.jpg
                  >
                  > The following code works nicely, except for one (probably obvious)
                  > problem...
                  >
                  > $count=1;
                  > do {
                  > $random = rand(1,50);
                  > echo "<img src='images/$random.jpg'>";
                  > $count++;
                  > }
                  > while ($count<5);
                  >
                  > The problem is that there is nothing to stop images appearing more than
                  > once. I do not want this to happen...
                  >
                  > Any ideas on a possible solution?
                  >
                  > TIA
                  >
                  > Mark
                  >[/color]


                  Comment

                  • Dominik Susmel

                    #10
                    Re: Not generating the same random number twice....

                    - seed the rand
                    - put nubers in array with array_rand
                    - use array_unique to initialize duplicate entries with 0
                    - do some magic to 0 numbers in contrast to existing stuff in array

                    --
                    Dominik Susmel | art director
                    www.vongestern.com | vonGestern art company . Zagreb, Croatia


                    Comment

                    • Geoff Berrow

                      #11
                      Re: Not generating the same random number twice....

                      I noticed that Message-ID:
                      <1118689179.0bf e721d1be71944ad 69de19a67d3613@ teranews> from Mark
                      contained the following:
                      [color=blue]
                      >The problem is that there is nothing to stop images appearing more than
                      >once. I do not want this to happen...
                      >
                      >Any ideas on a possible solution?[/color]

                      The following picks lottery balls (6 unique balls out of 49) Trivial to
                      adapt it to what you want.

                      <html>
                      <body style="color:re d"><?php

                      for($i=1;$i<50; $i++){
                      $balls[]=$i;
                      }

                      for($i=0;$i<6;$ i++){
                      $key=array_rand ($balls);
                      $ballschosen[]=$balls[$key];
                      unset($balls[$key]);
                      }

                      asort($ballscho sen);

                      foreach($ballsc hosen as $choice){
                      print"$choice ";
                      }

                      ?>
                      </body>
                      </html>

                      --
                      Geoff Berrow 011000100110110 0010000000110
                      001101101011011 001000110111101 100111001011
                      100110001101101 111001011100111 010101101011

                      Comment

                      • Shelly

                        #12
                        Re: Not generating the same random number twice....


                        <chernyshevsky@ hotmail.com> wrote in message
                        news:1118693141 .851760.37230@z 14g2000cwz.goog legroups.com...[color=blue]
                        > I'm just guessing that the script involves paging through a list of
                        > fifty images, five at a time. If that's case you'd need to have the
                        > same array as you go from page to page. Otherwise then, yes, as you
                        > said, you can just pop 5 numbers off the array.
                        >
                        > Another way to maintain the same randomized array across pages is to
                        > seed the random number engine with a fixed number, like today's date. A
                        > useful trick when you don't want to use session.
                        >[/color]

                        Isn't this doing double work? The shuffle randomizes the array. Then, all
                        you need to do is take the first five elements, since they are already in
                        random order. -- or am I missing something?

                        Shelly


                        Comment

                        • Ewoud Dronkert

                          #13
                          Re: Not generating the same random number twice....

                          On Mon, 13 Jun 2005 23:58:32 +0200, Dominik Susmel wrote:[color=blue]
                          > - seed the rand[/color]

                          Not needed as of PHP4.2.0
                          [color=blue]
                          > - put nubers in array with array_rand[/color]

                          That is not how array_rand() works, please see http://php.net/array-rand
                          [color=blue]
                          > - use array_unique to initialize duplicate entries with 0[/color]

                          Duplicate entries?! Bad algorithm. Also, that is not how array_unique()
                          works, please see http://php.net/array-unique
                          [color=blue]
                          > - do some magic to 0 numbers in contrast to existing stuff in array[/color]

                          This is really helpful.


                          --
                          Firefox Web Browser - Rediscover the web - http://getffox.com/
                          Thunderbird E-mail and Newsgroups - http://gettbird.com/

                          Comment

                          • Ewoud Dronkert

                            #14
                            Re: Not generating the same random number twice....

                            On Mon, 13 Jun 2005 23:54:08 +0100, Geoff Berrow wrote:[color=blue]
                            > for($i=1;$i<50; $i++){
                            > $balls[]=$i;
                            > }[/color]

                            See http://php.net/range
                            [color=blue]
                            > for($i=0;$i<6;$ i++){
                            > $key=array_rand ($balls);
                            > $ballschosen[]=$balls[$key];
                            > unset($balls[$key]);
                            > }[/color]

                            See http://php.net/shuffle
                            [color=blue]
                            > asort($ballscho sen);[/color]

                            Why use asort when you don't use the keys? See http://php.net/asort
                            [color=blue]
                            > foreach($ballsc hosen as $choice){
                            > print"$choice ";
                            > }[/color]



                            --
                            Firefox Web Browser - Rediscover the web - http://getffox.com/
                            Thunderbird E-mail and Newsgroups - http://gettbird.com/

                            Comment

                            • nemo

                              #15
                              Re: Not generating the same random number twice....

                              [snip]
                              All these much more sophisticated solutions make me wonder where I went
                              wrong in the early days.

                              while $Result etc
                              {
                              $Query="select image_filename from Tablename order by rand() limit 5";
                              images[]=$Row[image_filename];
                              }

                              Then position $images[0] $images[1] $images[2] where you want them.

                              Is there a prize for the neatest one? </pant-pant>

                              Comment

                              Working...