Hello my goal is to add the same values in an array and remove the repeated values then add the sum of these repeated values in the same array in a repetitive way until all the elements of the array will be distinct.
I made this code but it does it just once, how to repeat this action several times until the good result? thanks
function magic($arr)
{
$result = array_filter(array_count_values($arr), function ($el) {
return $el > 1;
});
foreach ($result as $k => $val) {
$a[] = $k;
$b[] = $k * $val;
}
$c[] = array_merge(array_diff($arr, $a), $b);
return $c;
}
print_r(magic([5, 5, 8, 8, 10, 9,20, 7, 7]));//found:[10,9,20,10,16,14] excpected:[9,40,14,16]( stape to find result:[10,9,20,10,16,14]==>[20,9,20,16,14]==>[9,40,14,16])
My Answer:
> 1;_ });__ $sum = array_sum($result);__ $arr = array_merge(array_diff($arr, array_keys($result)), [$sum]);__ return $arr;_}_$arr = [1, 2, 2, 3, 3, 3];_for ($i = 0; $i < count($arr); $i++)_{__ $arr = magic($arr);_}_print_r($arr);
Rate this post
4 of 5 based on 7860 votesComments