Last active
June 1, 2018 20:32
-
-
Save CMCDragonkai/29c42c0c3ffd834c9dea to your computer and use it in GitHub Desktop.
PHP: Cumulative/Prefix Summing. Use these functions to sum up a numeric array for subsequent processing.
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 | |
// count inclusive from x to y keys (x and y keys are the keys for the prefix sum, not the keys of the original array) | |
function cumulative_slice($prefix, $x, $y){ | |
return $prefix[$y] - $prefix[$x]; | |
} | |
// here's a more flexible function: | |
// run with X, Y when using original array indexes | |
// run with X, null, Z when using cumulative array indexes | |
function cumulative_range_sum($cumulative, $X, $Y, $Z = null){ | |
// range summing is between the X index inclusive, to the Y index inclusive, which requires Z to be Y+1 | |
if(is_null($Z)){ | |
$Z = $Y + 1; | |
} | |
return $cumulative[$Z] - $cumulative[$X]; | |
} |
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 cumulative_sum($A){ | |
$length = count($A); | |
$summed = array_fill(0, $length + 1, 0); | |
for($i = 1; $i <= $length; $i++){ | |
$summed[$i] = $summed[$i - 1] + $A[$i - 1]; | |
} | |
return $summed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment