Say I have an integer $M$. Is there a one-line command to create a partition of $M$ into $k$ integers s.t. the difference between any two integers is as small as possible?
For example, with $M = 100$ and $k = 10$, we would create the partition: {10,10,10,10,10,10,10,10,10,10}. However, for $k = 7$, we might have the partition: {14,14,14,14,14,14,16}, or better {14,14,14,14,14,15,15}.
For a partial solution, you can of course write:
M = 100;
k = 7;
BalancedPartition = Array[Floor[M/k] &, k];
BalancedPartition[[k]] += M - k*Floor[M/k];
BalancedPartition
{14, 14, 14, 14, 14, 14, 16}
Answer
I do not know single command to do this (it does not imply it does not exist:)). But it is two-line command:
dec[val_, par_] :=With[{ip = IntegerPart[val/par], md = Mod[val, par]},
ConstantArray[ip, par-md]~Join~ConstantArray[ip+1, md]]
dec[100, 10]
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}
dec[100, 7]
{14, 14, 14, 14, 14, 15, 15}
This is straightforward method: for k
-integer components md=Mod[val,k] ε [0, k-1]
so it is adding 1
to md
last positions of final list.
One could use Quotient[val,par]
or Floor[val/par]
insted of IntegerPart
.
Edit. Also:
ConstantArray in place of Table will make this faster. – Michael E2
So I swapped them.
Comments
Post a Comment