Random Number Question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul C-T

    Random Number Question

    Hi,

    Is there a way to repeat a set of code until a certain if statement is
    satisfied. If it is then to exit the loop and if not repeat the code?

    Say I want to write a card game application in PHP and I want to chose a
    card from the deck $card1 = rand(1,52); gets me my first card.

    I need to record which card has been dealt so I have a variable $dealt which
    starts out as a string of 52 zeros. I update the position of $card1 in the
    $dealt string to "1".

    So the 5 of Spades makes $dealt = "00001000000000 0 ..."

    I want to choose another card so I use $card2 = rand(1,52); and then need to
    check if it has already been dealt. If the position in $dealt is a 1 then I
    need to repeat the random number code until it is a 0 when I can update it
    to a 1 and move on ...

    Or is there a better way of doing this sort of thing ??

    Help, as always, appreciated.

    Paul.


  • steve

    #2
    Re: Random Number Question

    "Paul C-T" wrote:[color=blue]
    > Hi,
    >
    > Is there a way to repeat a set of code until a certain if statement[/color]
    is[color=blue]
    > satisfied. If it is then to exit the loop and if not repeat the[/color]
    code?[color=blue]
    >
    > Say I want to write a card game application in PHP and I want to[/color]
    chose[color=blue]
    > a
    > card from the deck $card1 = rand(1,52); gets me my first card.
    >
    > I need to record which card has been dealt so I have a variable[/color]
    $dealt[color=blue]
    > which
    > starts out as a string of 52 zeros. I update the position of[/color]
    $card1[color=blue]
    > in the
    > $dealt string to "1".
    >
    > So the 5 of Spades makes $dealt = "00001000000000 0 ..."
    >
    > I want to choose another card so I use $card2 = rand(1,52); and[/color]
    then[color=blue]
    > need to
    > check if it has already been dealt. If the position in $dealt is a[/color]
    1[color=blue]
    > then I
    > need to repeat the random number code until it is a 0 when I can
    > update it
    > to a 1 and move on ...
    >
    > Or is there a better way of doing this sort of thing ??
    >
    > Help, as always, appreciated.
    >
    > Paul.[/color]

    Paul, Yes, can be done. You make an array of all the cards (n cards).
    You pick a random number between 1 and n. When a number is picked,
    you simply take the card out of the array, so now you have one less
    card in the array. So now you pick from 1 to (n-1) and so on.

    You can use php’s rand function.

    Also you can unset any item in the array. The problem would be that
    the indecis would not reorganize, and e.g. when you remove item a,
    item (a+1) would still have the same index.

    So even though there is probably a better solution (anyone?) you can
    do:
    $my_array = array_merge( array(), $my_array);
    which reorganizes the index, and you can continue iterating.

    --
    http://www.dbForumz.com/ This article was posted by author's request
    Articles individually checked for conformance to usenet standards
    Topic URL: http://www.dbForumz.com/PHP-Random-N...ict134850.html
    Visit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbForumz.com/eform.php?p=450349

    Comment

    • Gordon Burditt

      #3
      Re: Random Number Question

      >Is there a way to repeat a set of code until a certain if statement is[color=blue]
      >satisfied. If it is then to exit the loop and if not repeat the code?[/color]

      This is generally called a while loop. Depending on your exact
      wording, you may need to negate the condition.
      [color=blue]
      >Say I want to write a card game application in PHP and I want to chose a
      >card from the deck $card1 = rand(1,52); gets me my first card.
      >
      >I need to record which card has been dealt so I have a variable $dealt which
      >starts out as a string of 52 zeros. I update the position of $card1 in the
      >$dealt string to "1".
      >
      >So the 5 of Spades makes $dealt = "00001000000000 0 ..."
      >
      >I want to choose another card so I use $card2 = rand(1,52); and then need to
      >check if it has already been dealt. If the position in $dealt is a 1 then I
      >need to repeat the random number code until it is a 0 when I can update it
      >to a 1 and move on ...[/color]

      This can take a LOT of time especially when you get to the point
      where you have only 2 cards left in the deck, and it gets even worse
      when you use multiple "standard" 52-card decks.

      Random shuffling is usually done like this:

      Make an array with indexes 0 .. N-1 for N cards. Populate the array.
      Select a card by selecting a random integer between 0 and N-1 inclusive.
      This is the index of your chosen card. Now swap that card in the
      array with card N-1, then decrement N. Repeat to draw more cards until
      you don't need any more, or you run out of cards (N == 0).

      Gordon L. Burditt

      Comment

      • Geoff Berrow

        #4
        Re: Random Number Question

        I noticed that Message-ID: <cecnbp$md5@lib rary1.airnews.n et> from Gordon
        Burditt contained the following:
        [color=blue]
        >Random shuffling is usually done like this:
        >
        >Make an array with indexes 0 .. N-1 for N cards. Populate the array.
        >Select a card by selecting a random integer between 0 and N-1 inclusive.
        >This is the index of your chosen card. Now swap that card in the
        >array with card N-1, then decrement N. Repeat to draw more cards until
        >you don't need any more, or you run out of cards (N == 0).[/color]


        shuffle() and array_rand() also seem useful.
        --
        Geoff Berrow (put thecat out to email)
        It's only Usenet, no one dies.
        My opinions, not the committee's, mine.
        Simple RFDs http://www.ckdog.co.uk/rfdmaker/

        Comment

        • Paul C-T

          #5
          Re: Random Number Question

          Thanks for the advice ... seems like I need to do a bit more flowcharting of
          the problem ... and investigate some new PHP function.

          :-)

          Much obliged.

          Paul.


          Comment

          • Pjotr Wedersteers

            #6
            Re: Random Number Question

            Paul C-T wrote:[color=blue]
            > Hi,
            >
            > Is there a way to repeat a set of code until a certain if statement is
            > satisfied. If it is then to exit the loop and if not repeat the code?
            >
            > Say I want to write a card game application in PHP and I want to
            > chose a card from the deck $card1 = rand(1,52); gets me my first card.
            >
            > I need to record which card has been dealt so I have a variable
            > $dealt which starts out as a string of 52 zeros. I update the
            > position of $card1 in the $dealt string to "1".
            >
            > So the 5 of Spades makes $dealt = "00001000000000 0 ..."
            >
            > I want to choose another card so I use $card2 = rand(1,52); and then
            > need to check if it has already been dealt. If the position in
            > $dealt is a 1 then I need to repeat the random number code until it
            > is a 0 when I can update it to a 1 and move on ...
            >
            > Or is there a better way of doing this sort of thing ??
            >
            > Help, as always, appreciated.
            >
            > Paul.[/color]
            Ah, finally someone doing something I know a bit about, lol!
            Paul, there are some things you may want to consider. First of all,
            shuffling can be done easy using shuffle (), which auto-shuffles your array
            of cards. Then just deal from the top or bottom. There is also the Mersenne
            Twister Random function (quicker) you can use. Check php manual for that.
            For home use the shuffle () function is very comfortable in use.

            But there is a catch when dealing and shuffling cards. A deck of cards can
            be stacked in 2^52 ways. The default randomizer function is NOT capable of
            doing all these permutations, simply because its seed and reach is too low.
            So unless you are doing this just for fun, beware your randomly shuffled
            deck is not exactly like having a real deck of cards. Also be careful with
            the predictability. Cardplaying sites use all kinds of true random input
            (mouse movement etc) from their users to seed the randomizers.

            There are better/faster randomizers available online, including ones hat
            have a range broader then 2^52. Not sure if they are available for PHP btw,
            but you could always use an external randomizer if need be using exec()
            Need more, just holler!
            Pjotr


            Comment

            • Chung Leong

              #7
              Re: Random Number Question

              "Geoff Berrow" <blthecat@ckdog .co.uk> wrote in message
              news:ovsjg01gmu l0msm90hbhtii8v sppnjv7ti@4ax.c om...[color=blue]
              > I noticed that Message-ID: <cecnbp$md5@lib rary1.airnews.n et> from Gordon
              > Burditt contained the following:
              >[color=green]
              > >Random shuffling is usually done like this:
              > >
              > >Make an array with indexes 0 .. N-1 for N cards. Populate the array.
              > >Select a card by selecting a random integer between 0 and N-1 inclusive.
              > >This is the index of your chosen card. Now swap that card in the
              > >array with card N-1, then decrement N. Repeat to draw more cards until
              > >you don't need any more, or you run out of cards (N == 0).[/color]
              >
              >
              > shuffle() and array_rand() also seem useful.
              > --
              > Geoff Berrow (put thecat out to email)
              > It's only Usenet, no one dies.
              > My opinions, not the committee's, mine.
              > Simple RFDs http://www.ckdog.co.uk/rfdmaker/[/color]

              Shuffle() is the right one to use in this case. Just shuttle the array then
              pop the items off one at a time with array_pop(). That mimicks exactly what
              happens when you're dealing cards. Array_rand() wouldn't work since it
              doesn't prevent the same item being picked again.


              Comment

              • Chung Leong

                #8
                Re: Random Number Question


                "Pjotr Wedersteers" <x33159@westert erp.com> wrote in message
                news:410a1d69$0 $30782$e4fe514c @dreader16.news .xs4all.nl...[color=blue]
                > Paul C-T wrote:[color=green]
                > > Hi,
                > >
                > > Is there a way to repeat a set of code until a certain if statement is
                > > satisfied. If it is then to exit the loop and if not repeat the code?
                > >
                > > Say I want to write a card game application in PHP and I want to
                > > chose a card from the deck $card1 = rand(1,52); gets me my first card.
                > >
                > > I need to record which card has been dealt so I have a variable
                > > $dealt which starts out as a string of 52 zeros. I update the
                > > position of $card1 in the $dealt string to "1".
                > >
                > > So the 5 of Spades makes $dealt = "00001000000000 0 ..."
                > >
                > > I want to choose another card so I use $card2 = rand(1,52); and then
                > > need to check if it has already been dealt. If the position in
                > > $dealt is a 1 then I need to repeat the random number code until it
                > > is a 0 when I can update it to a 1 and move on ...
                > >
                > > Or is there a better way of doing this sort of thing ??
                > >
                > > Help, as always, appreciated.
                > >
                > > Paul.[/color]
                > Ah, finally someone doing something I know a bit about, lol!
                > Paul, there are some things you may want to consider. First of all,
                > shuffling can be done easy using shuffle (), which auto-shuffles your[/color]
                array[color=blue]
                > of cards. Then just deal from the top or bottom. There is also the[/color]
                Mersenne[color=blue]
                > Twister Random function (quicker) you can use. Check php manual for that.
                > For home use the shuffle () function is very comfortable in use.
                >
                > But there is a catch when dealing and shuffling cards. A deck of cards can
                > be stacked in 2^52 ways. The default randomizer function is NOT capable of
                > doing all these permutations, simply because its seed and reach is too[/color]
                low.[color=blue]
                > So unless you are doing this just for fun, beware your randomly shuffled
                > deck is not exactly like having a real deck of cards. Also be careful with
                > the predictability. Cardplaying sites use all kinds of true random input
                > (mouse movement etc) from their users to seed the randomizers.[/color]

                Errr, isn't that as good as casinos asking their patrons to shuffle the
                cards?

                Modern CPUs have hardware random number generator built-in so it seems a
                better idea to hit /dev/random when you need a truely random number.


                Comment

                • Pjotr Wedersteers

                  #9
                  Re: Random Number Question

                  Chung Leong wrote:
                  [color=blue][color=green]
                  >> Ah, finally someone doing something I know a bit about, lol!
                  >> Paul, there are some things you may want to consider. First of all,
                  >> shuffling can be done easy using shuffle (), which auto-shuffles
                  >> your array of cards. Then just deal from the top or bottom. There is
                  >> also the Mersenne Twister Random function (quicker) you can use.
                  >> Check php manual for that. For home use the shuffle () function is
                  >> very comfortable in use.
                  >>
                  >> But there is a catch when dealing and shuffling cards. A deck of
                  >> cards can be stacked in 2^52 ways. The default randomizer function
                  >> is NOT capable of doing all these permutations, simply because its
                  >> seed and reach is too low. So unless you are doing this just for
                  >> fun, beware your randomly shuffled deck is not exactly like having a
                  >> real deck of cards. Also be careful with the predictability.
                  >> Cardplaying sites use all kinds of true random input (mouse movement
                  >> etc) from their users to seed the randomizers.[/color]
                  >
                  > Errr, isn't that as good as casinos asking their patrons to shuffle
                  > the cards?
                  >
                  > Modern CPUs have hardware random number generator built-in so it
                  > seems a better idea to hit /dev/random when you need a truely random
                  > number.[/color]

                  True random generator in a computer ? Me thinks that's a bit of an
                  impossibility, unless it takes in analog signals from somewhere.
                  And the problem is the seeding of the (pseudo) randomizer plus the fact most
                  randomizers don't cover the full range to 2^52.


                  Comment

                  • Tim Van Wassenhove

                    #10
                    Re: Random Number Question

                    In article <410b8543$0$566 $e4fe514c@news. xs4all.nl>, Pjotr Wedersteers wrote:[color=blue]
                    > Chung Leong wrote:
                    >[color=green][color=darkred]
                    >>> Ah, finally someone doing something I know a bit about, lol!
                    >>> Paul, there are some things you may want to consider. First of all,
                    >>> shuffling can be done easy using shuffle (), which auto-shuffles
                    >>> your array of cards. Then just deal from the top or bottom. There is
                    >>> also the Mersenne Twister Random function (quicker) you can use.
                    >>> Check php manual for that. For home use the shuffle () function is
                    >>> very comfortable in use.
                    >>>
                    >>> But there is a catch when dealing and shuffling cards. A deck of
                    >>> cards can be stacked in 2^52 ways. The default randomizer function
                    >>> is NOT capable of doing all these permutations, simply because its
                    >>> seed and reach is too low. So unless you are doing this just for
                    >>> fun, beware your randomly shuffled deck is not exactly like having a
                    >>> real deck of cards. Also be careful with the predictability.
                    >>> Cardplaying sites use all kinds of true random input (mouse movement
                    >>> etc) from their users to seed the randomizers.[/color]
                    >>
                    >> Errr, isn't that as good as casinos asking their patrons to shuffle
                    >> the cards?
                    >>
                    >> Modern CPUs have hardware random number generator built-in so it
                    >> seems a better idea to hit /dev/random when you need a truely random
                    >> number.[/color]
                    >
                    > True random generator in a computer ? Me thinks that's a bit of an
                    > impossibility, unless it takes in analog signals from somewhere.
                    > And the problem is the seeding of the (pseudo) randomizer plus the fact most
                    > randomizers don't cover the full range to 2^52.[/color]

                    I've found network traffic dumps to be more than random enough to seed the
                    randomizer ;)

                    --
                    Tim Van Wassenhove <http://home.mysth.be/~timvw>

                    Comment

                    • Andy Hassall

                      #11
                      Re: Random Number Question

                      On Sat, 31 Jul 2004 13:40:55 +0200, "Pjotr Wedersteers" <x33159@westert erp.com>
                      wrote:
                      [color=blue][color=green]
                      >> Modern CPUs have hardware random number generator built-in so it
                      >> seems a better idea to hit /dev/random when you need a truely random
                      >> number.[/color]
                      >
                      >True random generator in a computer ? Me thinks that's a bit of an
                      >impossibilit y, unless it takes in analog signals from somewhere.
                      >And the problem is the seeding of the (pseudo) randomizer plus the fact most
                      >randomizers don't cover the full range to 2^52.[/color]

                      Hardware RNG's, at least on Intel chips, use "thermal noise" to generate their
                      values, making them pretty reasonably random. They're certainly not
                      pseudo-random based off an algorithm, they're based on a randomly fluctuating
                      physical property.

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

                      Comment

                      • Pjotr Wedersteers

                        #12
                        Re: Random Number Question

                        Andy Hassall wrote:[color=blue]
                        > On Sat, 31 Jul 2004 13:40:55 +0200, "Pjotr Wedersteers"
                        > <x33159@westert erp.com> wrote:
                        >[color=green][color=darkred]
                        >>> Modern CPUs have hardware random number generator built-in so it
                        >>> seems a better idea to hit /dev/random when you need a truely random
                        >>> number.[/color]
                        >>
                        >> True random generator in a computer ? Me thinks that's a bit of an
                        >> impossibility, unless it takes in analog signals from somewhere.
                        >> And the problem is the seeding of the (pseudo) randomizer plus the
                        >> fact most randomizers don't cover the full range to 2^52.[/color]
                        >
                        > Hardware RNG's, at least on Intel chips, use "thermal noise" to
                        > generate their values, making them pretty reasonably random. They're
                        > certainly not pseudo-random based off an algorithm, they're based on
                        > a randomly fluctuating physical property.[/color]

                        That's cool! (or hot). Indeed, if analog data is the randomizer source, true
                        randomness can be had. Any idea on the range of this randomizer ? Or links
                        to good in depth articles ? Thanks! Very happy with this, if I can use that
                        I can throw the soundcardnoise/input based randomizer out!
                        Pjotr


                        Comment

                        • RootShell

                          #13
                          Re: Random Number Question

                          I can share with you the code i use for my random routine (isnt perfect but
                          works) ;)

                          here it goes.....


                          // FUNCTION TO TRY AND MAKE A BETTER RANDOM NUMBER
                          function make_seed() {
                          list($usec, $sec) = explode(' ', microtime());
                          return (float) $sec + ((float) $usec * 100000);
                          }

                          $solucao = 0
                          $options = 1
                          srand((double)m icrotime()*intv al(rand(1,10000 00)));
                          $respostas[1] = rand (1,52);
                          $solucao++;
                          while ($solucao <= $options)
                          {
                          srand(make_seed ());
                          $pergunta = rand(1, 52);
                          if (!in_array($per gunta, $respostas))
                          {
                          $respostas[$solucao] = $pergunta;
                          $solucao++;
                          }
                          }

                          print_r ($respostas); // PRINTS THE ARRAY WITH UNIQUE CARDS ALREADY ADDED

                          *************** *************** *************** ******
                          explanation:
                          *************** *************** *************** ******
                          you say how many cards ($options) you want to add to the already picked
                          cards in the example 1


                          --
                          ZXSpectrum "Name The Game" - Can you guess the name of ZXSpectrum games,
                          just by looking at a ingame picture? Well you can find out if you can (or
                          not) at.... http:/ntg.docaj.net
                          --


                          Comment

                          • Brad Kent

                            #14
                            Re: Random Number Question

                            Also, I didn't see this mentioned...

                            rather than doing rand(1,52) each time through the loop and subsequent
                            multiple attempts to "draw" a random number that hasn't already been
                            picked, why not do a "real world" approach and only pick a random num
                            from what is avail?

                            have a $current_deck array or $cards_left array..
                            after you "draw" a card: unset($current_ deck[card_x]);

                            you can get a random card from this deck with
                            $rand_card = array_rand($cur rent_deck);

                            complete psudo code:

                            while ( sizeof($current _deck) > 0 )
                            {
                            // this code is executed exactly 52 times
                            $rand_card = array_rand($cur rent_deck);
                            unset($current_ deck[$rand_card]);
                            }


                            "Paul C-T" <paulcharltonth omson@hotmail.c om> wrote in message news:<4109b542$ 0$63371$ed2e19e 4@ptn-nntp-reader04.plus.n et>...[color=blue]
                            > Hi,
                            >
                            > Is there a way to repeat a set of code until a certain if statement is
                            > satisfied. If it is then to exit the loop and if not repeat the code?
                            >
                            > Say I want to write a card game application in PHP and I want to chose a
                            > card from the deck $card1 = rand(1,52); gets me my first card.
                            >
                            > I need to record which card has been dealt so I have a variable $dealt which
                            > starts out as a string of 52 zeros. I update the position of $card1 in the
                            > $dealt string to "1".
                            >
                            > So the 5 of Spades makes $dealt = "00001000000000 0 ..."
                            >
                            > I want to choose another card so I use $card2 = rand(1,52); and then need to
                            > check if it has already been dealt. If the position in $dealt is a 1 then I
                            > need to repeat the random number code until it is a 0 when I can update it
                            > to a 1 and move on ...
                            >
                            > Or is there a better way of doing this sort of thing ??
                            >
                            > Help, as always, appreciated.
                            >
                            > Paul.[/color]

                            Comment

                            • Pjotr Wedersteers

                              #15
                              Re: Random Number Question

                              Paul C-T wrote:[color=blue]
                              > Thanks for the advice ... seems like I need to do a bit more
                              > flowcharting of the problem ... and investigate some new PHP function.
                              >
                              > :-)
                              >
                              > Much obliged.
                              >
                              > Paul.[/color]

                              Yw. Some nice background on real-life issues for poker-sites (applies to any
                              similar gametype of course)
                              Quite a good explanation:



                              Comment

                              Working...