I need to find a "greatest common" array for given arrays in PHP (I'm not even sure what that term should be. What I mean is an array the elements of which can be sequencially combined to form the same elements of the input arrays). The input arrays may have different count() results, but they are always unidimensional, always contain only integers and always have the same array_sum() result.
Example:
$a = array(4,6);
$b = array(5,5);
$c = array(5,1,4);
What is the best way to find (in this case) this array
$gca = array(4,1,1,4);
?
Things got a lot easier after transforming those numbers in totals, instead of working with intervals/durations. This way, the original arrays turned into these:
$a = array(4,10);
$b = array(5,10);
$c = array(5,6,10);
Then it was a matter of merging the arrays, removing duplicate values and sorting, just before converting the elements back to intervals. Output of the proposed function is
array(4,1,1,4)
as intended.
Any improvement on the function is appreciated.
$arr[] = array(4,6);
$arr[] = array(5,5);
$arr[] = array(5,1,4);
function findCommonDurations($arr) {
$absolute_result = $result = array();
foreach($arr as $key => $value) {
$temp_arr = array();
$so_far = 0;
foreach($value as $key2 => $value2) {
$temp_arr[] = $value2 + $so_far;
$so_far += $value2;
}
$absolute_result = array_merge($absolute_result, $temp_arr);
}
$absolute_result = array_unique($absolute_result);
sort($absolute_result);
$result[0] = $absolute_result[0];
for ($i = 1, $n = count($absolute_result); $i < $n; $i++) {
$result[] = $absolute_result[$i] - $absolute_result[$i-1];
}
return($result);
}
print_r(findCommonDurations($arr));