3

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]
Tyr1on
  • 1,999
  • 2
  • 13
  • 20
  • I don't quite get what you're trying to achieve. Distributing numbers 1 to x into n arrays or splitting x into n integer components doesn't seem to hard. – Thomas Apr 14 '21 at 07:16

1 Answers1

1

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.

MBo
  • 77,366
  • 5
  • 53
  • 86