random number generator-- need separation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cherryst152
    New Member
    • Nov 2007
    • 16

    #1

    random number generator-- need separation

    Ok, so i have a php random number generator that creates two unique numbers between 1 and 10, what i want to add that i can't figure out for the life of me is how to implement that these two numbers will always have a separation of 4. For example, 1 and 6...or even 2 and 9.... but never 2 and 3... or 4 and 7.

    <?php
    $arr=array();
    while(count($ar r)<2){
    $x=mt_rand(1,10 );
    if (!in_array($x,$ arr)){
    $arr[]=$x;
    echo "$x<br>";
    }
    }
    ?>

    Thanks in advance.
  • cherryst152
    New Member
    • Nov 2007
    • 16

    #2
    bump... please... any help is appreciated

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      [I they must have a seperation of four, then you can only really have one random number.
      So generate one random number then add or subtract four to generate the second.
      If you need to randomise whether adding or subtracting then generate another rand()
      between -1 and +1 and multiply the second number by this, but eliminate zeroes.

      Comment

      • Motoma
        Recognized Expert Specialist
        • Jan 2007
        • 3236

        #4
        Essentially, you are only working with 1 random number, and one complimentary number which follows the rule that it is 4 more than the random number, and less than 10. Therefore, your random number is constrained to a minimum of 1 and a maximum of 6 (10 - 4).

        [code=php]
        <?php

        $x = mt_rand(1,6);
        $arr = array($x, $x+6);

        ?>
        [/code]

        Comment

        Working...