3v4l.org

run code in 300+ PHP versions simultaneously
<?php $candiesTests = [ [1, 1, 2, 3], // Test1 => 1,3 [1, 1, 2, 3, 4], // Test2 => 1,4 [1, 1, 2, 2, 3, 4, 5, 5], // Test3 => 1,2,5,5 [1, 1, 2, 2, 3, 4, 5, 5, 1, 1, 5], // Test4 => 1,1,1,2,5 ]; function distributeCandies(array $candies): array { $quota = ceil(count($candies) / 2); // Berit's share $adam = []; // fill first $berit = []; // the leftovers $candyCounts = array_count_values($candies); ksort($candyCounts); while ($candyCounts) { foreach ($candyCounts as $candy => &$count) { $adam[] = $candy; --$count; if (!$count) { unset($candyCounts[$candy]); } if (count($adam) == $quota) { break 2; } } } foreach ($candyCounts as $candy => $count) { array_push($berit, ...array_fill(0, $count, $candy)); } return [$adam, $berit]; } foreach ($candiesTests as $candies) { $distribution = distributeCandies($candies); echo 'Adams candies: ' . implode(', ', $distribution[0]) . PHP_EOL . 'Berits candies: ' . implode(', ', $distribution[1]) . PHP_EOL . '---' . PHP_EOL; }

preferences:
131.44 ms | 409 KiB | 5 Q