Skip to content

Instantly share code, notes, and snippets.

@kapolos
Created September 8, 2015 12:39
Show Gist options
  • Save kapolos/f91571bfbce9e3f9c573 to your computer and use it in GitHub Desktop.
Save kapolos/f91571bfbce9e3f9c573 to your computer and use it in GitHub Desktop.
<?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