Skip to content

Instantly share code, notes, and snippets.

@codelikesuraj
Last active May 2, 2021 17:10
Show Gist options
  • Save codelikesuraj/3ba3198cd055ccce53f04c616c3211b9 to your computer and use it in GitHub Desktop.
Save codelikesuraj/3ba3198cd055ccce53f04c616c3211b9 to your computer and use it in GitHub Desktop.
Solution to "Algorithm Fridays (30-04-2021)" problem
<?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");
}
?>
@meekg33k
Copy link

meekg33k commented May 2, 2021

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

This is a clean and correct solution that passes most, not all of the test cases. I like that your solution is robust and handles unexpected or invalid input without throwing any runtime errors.

The one thing I want to say is, do you have a reason for creating a new array like you did on line 5? Also what is the result of your solution when one of the entries is 0?

@codelikesuraj
Copy link
Author

codelikesuraj commented May 2, 2021

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

This is a clean and correct solution that passes most, not all of the test cases. I like that your solution is robust and handles unexpected or invalid input without throwing any runtime errors.

The one thing I want to say is, do you have a reason for creating a new array like you did on line 5? Also what is the result of your solution when one of the entries is 0?

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.
meekg33k

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