Skip to content

Instantly share code, notes, and snippets.

@Modelizer
Created January 26, 2017 10:57
Show Gist options
  • Save Modelizer/22f906a9694ac1489ae18dadeca5e4f8 to your computer and use it in GitHub Desktop.
Save Modelizer/22f906a9694ac1489ae18dadeca5e4f8 to your computer and use it in GitHub Desktop.
An algo to replace all the natural numbers with zero (horizontally and vertically).
<?php
/**
* This is an algo to replace all the natural numbers with zero (horizontally and vertically).
* This was an interview question to solve.
*
* If you have more better solution with less iteration will be appreciated.
*
* @author Mohammed Mudasir <hello@mudasir.me>
**/
// Actual matrix
$matrix = [
[1, 3, 5, 7],
[9, 0, 4, 2],
[8, 4, 10, 1],
[9, 5, 1, 0],
];
// expected matrix
/**
*
* $matrix = [
* [1, 0, 5, 0],
* [0, 0, 0, 0],
* [8, 0, 10, 0],
* [0, 0, 0, 0],
* ];
*
**/
// Indexes will be store when ever "0" occurrence found.
$indexes = [];
// Looping to get indexes
foreach ($matrix as $row) {
foreach ($row as $key => $value) {
if ($value == 0) {
$indexes[] = $key;
}
}
}
// Only store unique indexes also getting only values out and fliping it to store as a key.
$indexes = array_flip(array_values(array_unique($indexes)));
// Start actual matrix iteration
foreach ($matrix as $matrixKey => $row) {
// If 0 is found in a row then replace whole row with zero
if (in_array(0, $row)) {
$matrix[$matrixKey] = array_fill(0, count($row), 0);
continue;
}
// Looping in a row to find zero is found in our store index $index
foreach ($row as $key => $value) {
if (isset($indexes[$key])) {
$matrix[$matrixKey][$key] = 0;
}
}
}
print_r($matrix);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment