The following requirements exist: first there are arrays
$arr = array(1 => 12, 2 => 23)Now, to split the array, generate a new array with the following number of new arrays:
$newArr = array( array(2, 7), array(2, 7), array(2, 9), array(1, 3), array(1, 9),)
The condition must be met:
1: The new array must have 5 items;
2: Must be divided by the largest value in the original array, and then the second large value ... , as to the number of each item to be split, decide for itself,
3: The first value in the second dimension of the split array is the original key, the value is the split value, and the first value in the two dimensions must be equal to the value corresponding to the original array key.
Reply content:
There are the following requirements: First, there are arrays $arr = array(1 => 12, 2 => 23) ; now to split the array, generate a new array with the following number of new arrays:
$newArr = array( array(2, 7), array(2, 7), array(2, 9), array(1, 3), array(1, 9),)
The condition must be met:
1: The new array must have 5 items;
2: Must be divided by the largest value in the original array, and then the second large value ... , as to the number of each item to be split, decide for itself,
3: The first value in the second dimension of the split array is the original key, the value is the split value, and the first value in the two dimensions must be equal to the value corresponding to the original array key.
Cabaret Show. I just stick to the answer. Skills:
- Think of it as a line segment and randomly select a number of points on top to cut it off. The sum of the lengths of each segment is necessarily correct and value.
- The title does not prohibit the result from appearing in 0, so the point is allowed to repeat.
- When the value is negative, the reversal is processed as positive.
2 = [1 = 0, 2 = 0];d efine ("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 = arr Ay_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); Do not prohibit the appearance of 0 without the need to weigh (if the problem is forbidden 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]);}