Oshay
Oshay

Reputation: 31

Random Numbers, Column and Row. PHP

Please excuse me as this is my first post and I am fairly new to any type of programming. I hope my question is clear, I am using Excel references as I think this explains what I am trying to do best.

I am trying to generate random numbers for a pool. I have 8 rows of numbers and each row contains 10 spots, 0 to 9. I want to have a random number in each row and make sure the the number does not repeat in each row.

Example Grid - 8 columns wide x 10 rows long.

I am repeating this scrip for each column, but I am getting the same number is rows and I want make sure that does not happen.

for ($i=1; $i<=10; $i++) {
            while (1) {
                $duplicate = 0;
                $num=rand(0,9);     
                for ($x=1; $x<$i; $x++) {
                    if ($NFC1[$x]==$num) { $duplicate = 1; }
                }

                if ($duplicate==0) {
                    $NFC1[$i]=$num;
                    break;
                }
            }
        }

This is the results, as you can see I have random numbers is each column but not in each row.

"4";"8";"5";"5";"0";"4";"2";"7"
"5";"9";"4";"3";"9";"9";"9";"0"
"9";"5";"1";"1";"5";"8";"6";"1"
"7";"4";"6";"2";"6";"7";"3";"3"
"2";"6";"8";"4";"7";"2";"7";"5"
"0";"1";"0";"7";"2";"1";"4";"6"
"1";"7";"9";"9";"4";"3";"0";"4"
"3";"0";"3";"0";"3";"5";"5";"9"
"8";"2";"7";"8";"1";"6";"8";"2"
"6";"3";"2";"6";"8";"0";"1";"8"

Upvotes: 3

Views: 592

Answers (1)

Brejk
Brejk

Reputation: 454

The answer from here addapted to non-square array may looks like below:

$rows = 10;    // Number of rows
$columns = 8;  // Number of columns

$row = range(0, $columns-1);
$column = range(0, $rows-1);

shuffle($row);
shuffle($column);

// Create an array
foreach ($row as $x => $value)
    foreach ($column as $y)
        $array[$y][$x] = $value++ % max($rows, $columns);

And if you want to see the result:

foreach($array as $r) {
    foreach($r as $number) {
        echo $number.' ';
    }
    echo "<br/>";
}

Upvotes: 1

Related Questions