Created
September 8, 2015 12:39
-
-
Save kapolos/f91571bfbce9e3f9c573 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Returns an array with each position filled with the product of all | |
* elements of the original array except for the one on the respective position | |
* | |
* @param array $arr | |
* | |
* @return array | |
*/ | |
function reducedProducts(Array $arr) | |
{ | |
$l2r = [1]; | |
$r2l = [1]; | |
$arrSize = count($arr); | |
for ($i = 0; $i < $arrSize - 1; $i++) { | |
$l2r[] = $arr[$i] * $l2r[(count($l2r) - 1)]; | |
$r2l[] = $arr[$arrSize - 1 - $i] * $r2l[(count($r2l) - 1)]; | |
} | |
$r2l = array_reverse($r2l); | |
return array_map(function ($x, $y) { | |
return $x * $y; | |
}, | |
$l2r, $r2l); | |
} | |
/* Usage */ | |
$arr = [1, 2, 3, 4]; | |
var_dump(reducedProducts($arr)); | |
//-> [24,12,8,6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment