0

I have two different functions, one that generates 5 random cards from value 0-51 (unique), and one function that contain an array containing those 5 cards, and an array that contains some of the numbers from array #1 that would be stored.

The function two function two is to replace new values to array #1 if the value is not in array #2. It seems to be something wrong here. after generating numbers for a bit i got:

array(27,18,37,27,45) 

returned from the newCards function.

Question: How can i fix newCards function 100% to do what it is supposed to do? (aka use first array, check if number is in 2nd array, if not, make unique here too) since here it went something wrong since it returned two of the same numbers.

code:

    function UniqueCards() {
        $result = array();

        while(count($result) != 5) {
            $rand = rand(0,51); // reads as 0 = 1, and 51 = 52. aka starts at zero.

            if(!in_array($rand,$result)){
                $result[] = $rand;
            }
        }

        return $result;
    }

    function newCards($input,$exclude) {
            $i = 0;
            $output = array();
            while($i < count($input)) {
                $rand = rand(0,51);

                if(in_array($input[$i], $exclude)) {
                    $output[$i] = $input[$i];
                    $i++;
                }

                else if(!in_array($rand, $input)){
                    $output[$i] = $rand;
                    $i++;
                }
            }
            return $output;



    }
maria
  • 207
  • 5
  • 22
  • 56
  • 1
    possible duplicate of [Generating UNIQUE Random Numbers within a range - PHP](http://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php) – bardzusny May 01 '15 at 19:44
  • Seems like you're using the code from this question: http://stackoverflow.com/q/29938271/3933332 , Did you looked at all other answers, which are there? – Rizier123 May 01 '15 at 19:44
  • yes. i tried. the only one there that is different and not killing the function by performance, are not complete, generating numbers way behind its purpose etc. – maria May 01 '15 at 19:59

1 Answers1

0

If you add checking if $rand is already in $output will it fix the problem?

function newCards($input,$exclude) {
    ...
    else if(!in_array($rand, $input) && !in_array($rand, $output)) {
        $output[$i] = $rand;
        $i++;
    }
   ...
}
Sergiy T.
  • 1,433
  • 1
  • 23
  • 25