Question

I have a list and I want to split it into sub lists with +/- 1 items.

Example

I have a list with 17 items in it. What I want is to split it into 4 sub lists like these

1.List = 5 elements
2.List = 4 elements
3.List = 4 elements
4.List = 4 elements

How can I do that? What algorithm I should use here?

Was it helpful?

Solution

Use integer division to get the items in each group and then use modular division to get the number of the first n groups that will have +1 item. For example: 17 items into 4 groups:

  • 17 / 4 = 4 - So there will be 4 groups with 4 elements.
  • 17 % 4 = 1 - So the first 1 groups will have an additional 1 element.

Another example:

  • 18 / 4 = 4 - So there will be 4 groups with 4 elements.
  • 18 % 4 = 2 - So the first 2 groups will have an additional 1 element.

OTHER TIPS

What you want is the Power Set of your original list. The more generic approach for retrieving the power set and the respective properties are given at the Power Set page at Wikipedia

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top