Page 1 of 1

Help with 2D array creation

Posted: Tue Feb 15, 2011 5:51 pm
by laurieloo89
Evening all:)

I'm new to this forum, so apologies if this problem has been previously covered or if I should be posting this in a different topic.

Just a quick question.
I'm needing to create a 2D array(4 rows and 4 columns) containing 16 random unique numbers between 1 and 60(inclusive). I'm still in the middle of learning PHP so I'm having a small problem coding.
I've created my 2D array already, but I'm having trouble with the unique numbers. Although I have the number unique to each row/column, I can't seem to get my head around being able to get each number unique to the overall 2D array.

Any help/advice would be much appreciated!

Re: Help with 2D array creation

Posted: Tue Feb 15, 2011 6:21 pm
by AbraCadaver
Code please. Each time you generate a random put it in a 1d tracking array. When you generate the number check in the tracking array to make sure it hasn't been used: in_array()

Re: Help with 2D array creation

Posted: Tue Feb 15, 2011 6:42 pm
by Jonah Bron
I feel like coding :)

Code: Select all

$rands = array();                            // create array to hold random numbers
for ($i = 0; $i < 16; $i++) {                // loop 16 times (4x4)
    do {                                     // use do...while to ensure uniqueness
        $num = rand(0, 60);                  // get a random number
    } while (in_array($num, $rands, true));  // make sure it's not already used
    $rands[] = $num;                         // add to list
}

$final = array();                            // create final 2d array
for ($i = 0; $i < 4; $i++) {                 // iterate 4 times for first dimension
    $temp1 = array();                        // create second dimension array
    for ($j = 0; $j < 4; $j++) {             // iterate 4 times for second dimension
        $temp1[] = array_pop($rands);        // grab number from list
    }
    $final[] = $temp1;                       // put 2nd dimension into first dimension
}