/*
Generate N random 1s in a zero-based matrix.
Strategy:
- Treat the matrix as a flat index space [0 .. rows*cols - 1].
- Randomly pick unique positions using a boolean helper array.
- Convert each chosen flat index back to (row, col).
- This avoids repeatedly searching for empty cells and keeps the logic simple.
*/
/* Print the matrix */
function printMatrix(array $matrix, int $rows, int $cols): void
{
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
echo $matrix[$r][$c] . ' ';
}
echo PHP_EOL;
}
}
/* Allocate a rows×cols matrix initialized to zero */
function allocateMatrix(int $rows, int $cols): array
{
$matrix = [];
for ($r = 0; $r < $rows; $r++) {
// Each row is initialized with zeros
$matrix[$r] = array_fill(0, $cols, 0);
}
return $matrix;
}
/* Generate N random 1s in a zero-based matrix */
function generateRandomMatrix(int $rows, int $cols, int $count): array
{
$total = $rows * $cols;
if ($count > $total) {
throw new InvalidArgumentException("Requested more 1s than available cells.");
}
$matrix = allocateMatrix($rows, $cols);
// Temporary array to mark chosen positions
$chosen = array_fill(0, $total, false);
// Draw unique positions
$placed = 0;
while ($placed < $count) {
$index = random_int(0, $total - 1);
if (!$chosen[$index]) {
$chosen[$index] = true;
$placed++;
}
}
// Convert flat indices to (row, col)
for ($i = 0; $i < $total; $i++) {
if ($chosen[$i]) {
$r = intdiv($i, $cols);
$c = $i % $cols;
$matrix[$r][$c] = 1;
}
}
return $matrix;
}
/* Example usage */
$rows = 5;
$cols = 7;
$numberOfOnes = 10;
$result = generateRandomMatrix($rows, $cols, $numberOfOnes);
printMatrix($result, $rows, $cols);
/*
run:
0 0 1 0 0 0 0
0 0 1 1 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 1
0 0 0 1 0 1 0
*/