Your task is to create a program or function, that when given an input list of nonnegative integers of length \$l \ge 2\$ and a nonnegative integer \$c\$ where \$2 \le c \le l\$, group the list into \$c\$ "clusters." What this means is, the average (population) variance* of all the groups should be as low as possible.
For example, [[0, 3], [4, 6]]
has an average variance of \$\frac{\frac{\left(0-\frac{0+3}{2}\right)^2+\left(3-\frac{0+3}{2}\right)^2}{2}+\frac{\left(4-\frac{4+6}{2}\right)^2+\left(6-\frac{4+6}{2}\right)^2}{2}}{2}\$ or \$1.625\$, while [[0], [3, 4, 6]]
has an average variance of \$\frac{\frac{\left(0-\frac{0}{1}\right)^2}{1}+\frac{\left(3-\frac{3+4+6}{3}\right)^2+\left(4-\frac{3+4+6}{3}\right)^2+\left(6-\frac{3+4+6}{3}\right)^2}{3}}{2}\$ or \$\frac{7}{9}\$, and \$\frac{7}{9} < 1.625\$, so the latter is the correct output for the first test case. The result will have the closest numbers placed together and the farthest numbers placed in different groups.
*This is calculated by squaring the distance between all the numbers in the list and the mean of it, and then taking the mean of those squared distances.
Rules
- Groups and numbers inside of the groups can be in any order.
- When there are multiple possible outputs with the same average variance, any of them is acceptable.
- Each group must have at least one number.
- Input and output may be in any convenient format.
- This is code-golf, so the shortest answer in bytes wins.
Test Cases
Input Output (sorted) [0, 3, 4, 6], 2 [[0], [3, 4, 6]] [0, 1, 2, 3], 2 [[0, 1], [2, 3]] [0, 1, 2, 3, 4], 2 [[0, 1], [2, 3, 4]] or [[0, 1, 2], [3, 4]] [10, 13, 6, 11, 8], 3 [[6, 8], [10, 11], [13]] [4, 2, 9], 3 [[2], [4], [9]] [1, 19, 8, 12, 3, 19], 3 [[1, 3], [8, 12], [19, 19]] [8, 8, 8, 8], 2 [[8], [8, 8, 8]] or [[8, 8], [8, 8]]
[[8], [8, 8, 8]] or [[8, 8], [8, 8]] or [[8, 8, 8], [8]]
aren't[[8], [8, 8, 8]]
and ` [[8, 8, 8], [8]]` same? \$\endgroup\$