Created
May 2, 2021 09:43
-
-
Save harmlessprince/d717962faef687e6a6d0b434f9c0587d to your computer and use it in GitHub Desktop.
Product of all other numbers an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); |
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
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.
Because if I run the code snippet below
Let me know what you think.