Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate N random 1s in a zero-based matrix with PHP

1 Answer

0 votes
/*
    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 

*/

 



answered 4 days ago by avibootz
...