Skip to content

Instantly share code, notes, and snippets.

@harmlessprince
Created May 2, 2021 09:43
Show Gist options
  • Save harmlessprince/d717962faef687e6a6d0b434f9c0587d to your computer and use it in GitHub Desktop.
Save harmlessprince/d717962faef687e6a6d0b434f9c0587d to your computer and use it in GitHub Desktop.
Product of all other numbers an array
<?php
function CalculateProducts($array)
{
//check if array is undefined
if (!$array) {
return [];
}
//check if array has length equal to zero
if (count($array) == 0) {
return [];
}
//check if array contains 0 or null
if (in_array(0, $array)) {
return [];
}
return array_map(function ($element) use ($array) {
return array_product($array) / $element;
}, $array);
}
$array = [4, 5, 10, 2];
print_r(CalculateProducts($array));
@meekg33k
Copy link

meekg33k commented May 2, 2021

Hello @harmlessprince, thank you for participating in Week 4 of Algorithm Fridays.

Decent and efficient solution, kudos to you! I like your edge case checks on line 6 and 10. However, your check shown below on line 14 makes your solution fail one one of the test cases.

   if (in_array(0, $array)) {
        return [];
    }

Because if I run the code snippet below

$initial_array = [4, 3, 0];
echo json_encode(CalculateProducts($initial_array), JSON_PRETTY_PRINT); ❌ // should return [0, 0, 12] but yours returns []

Let me know what you think.

@harmlessprince
Copy link
Author

I do not think this assertion is right.

On line 18, if 0 is included in the array, the result of the division will surely return undefined. now trying to use undefined to divide or multiply another number will return NAN.

If you don't mind pointing me to a solution that returns this output you stated , I will be glad to learn from it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment