Last active
May 2, 2021 17:10
-
-
Save codelikesuraj/3ba3198cd055ccce53f04c616c3211b9 to your computer and use it in GitHub Desktop.
Solution to "Algorithm Fridays (30-04-2021)" problem
This file contains hidden or 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 | |
// initial array entry | |
$initial_array = [4, 8, 2, 5, 2]; | |
// initialise variable to store the final array | |
$final_array = array(); | |
// get the number of elements in the initial array | |
$numberOfElements = count($initial_array); | |
if (!empty($initial_array) && is_array($initial_array) && $numberOfElements > 0){ | |
for($i=0; $i<$numberOfElements; $i++){ | |
// initialise a new index in final array and set it to 1 | |
$final_array[$i] = 1; | |
// multiply all index in the INITIAL array except the current index | |
// to get the value of the current index in the FINAL array | |
for($j=0; $j<$numberOfElements; $j++){ | |
if (!is_numeric($initial_array[$j])){ | |
// display error message | |
die("Elements in the array can only be numeric"); | |
} | |
// skip multiplication if index of INITIAL array | |
// matches the index of the FINAL array | |
if($j === $i){ | |
continue; | |
} | |
$final_array[$i] *= $initial_array[$j]; | |
} | |
} | |
// display final array - [ 160, 80, 320, 128, 320 ] | |
echo json_encode($final_array, JSON_PRETTY_PRINT); | |
}else { | |
// display error message | |
die ("Input array is not valid"); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your feedback.

I created a new array on line 5 to store the result of the multiplication.
In a situation when any of the entries is 0, all other indexes become 0 except for that one.