How to check if a given matrix is a sparse matrix (contains a large number of zeros) in PHP

1 Answer

0 votes
// A sparse matrix is a matrix in which the majority of elements are zero.

// Check if a matrix is sparse
function isSparse($matrix) {
    $zeroCount = 0;
    $rows = count($matrix);
    $cols = count($matrix[0]);

    // Count zeros
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            if ($matrix[$i][$j] == 0) {
                $zeroCount++;
            }
        }
    }

    // A matrix is sparse if more than half of its elements are zero
    return $zeroCount > ($rows * $cols) / 2;
}

$matrix = [
    [2, 0, 5, 0],
    [0, 4, 0, 0],
    [0, 8, 0, 9]
];


if (isSparse($matrix)) {
    echo "Matrix is sparse\n";
} else {
    echo "Matrix is not sparse\n";
}


/*
run:

Matrix is sparse

*/

 



answered 2 days ago by avibootz
...