Reputation: 2339
I am hitting a wall in coming up with an equation to this simple question. I need a different perspective coming up with an algorithm. I have a number x
and I want to distribute it to n
elements in a greedy manner.
For x=9, n=3
[1,2,3],[4,5,6],[7,8,9] OR [3,3,3]
For x=10, n=3
[1,2,3,4],[5,6,7],[8,9,10] OR [4,3,3]
For x=11, n=3
[1,2,3,4],[5,6,7,8],[9,10,11] OR [4,4,3]
For x=12, n=3
[1,2,3,4],[5,6,7,8],[9,10,11,12] OR [4,4,4]
Upvotes: 3
Views: 152
Reputation: 80287
As far as I understand, you need to get array like [4,4,3]
. So use integer division and modulo operation
smallvalue = x / n ; //integer division
largecount = x % n; //number of larger values
smallcount = n - largecount
Now fill array with largecount
quantity of smallvalue+1
and then with smallcount
of smallvalue
If you need result [1,2,3,4],[5,6,7,8],[9,10,11]
- use the same information to generate it.
Upvotes: 1