余兴节目。我就直接粘答案了。技巧:
<?php
header("Content-Type: text/plain; ");
$input = [1 => 12, 2 => 23];
$input = [1 => 0, 2 => 0];
define("TOTAL_SEGMENTS", 5);
$input_sorted = $input;
asort($input_sorted);
$segment_counts = [];
$segment_counts[0] = mt_rand(1, TOTAL_SEGMENTS - 1);
$segment_counts[1] = TOTAL_SEGMENTS - $segment_counts[0];
$result = [];
for ($i_slice = 0; $i_slice < 2; $i_slice++) {
$input_record = array_slice($input_sorted, -($i_slice + 1), 1, true);
$record_key = array_keys($input_record)[0];
$target_sum = array_values($input_record)[0];
$segment_count = $segment_counts[$i_slice];
if ($target_sum < 0) {
$negative_sum = true;
$target_sum = -$target_sum;
} else {
$negative_sum = false;
}
$positions = [0, $target_sum];
while (count($positions) < ($segment_count + 1)) {
$t = mt_rand(0, $target_sum);
array_push($positions, $t); //不禁止出现0的时候无需判重(如果禁止出现0这个题就麻烦了)
}
sort($positions);
for ($i = 0; $i < $segment_count; $i++) {
$value = $positions[$i + 1] - $positions[$i];
if ($negative_sum) { $value = -$value; }
array_push($result, [$record_key, $value]);
}
}
foreach ($result as $line) { printf("array(%d, %d), \n", $line[0], $line[1]); }