3

I have an array of size elements, and I have a function that will split it into roughly equal sections. It does this by setting the size of the first size-1 sections with size/num_of_sections, and setting the size of the last section with whatever is left. The code is simple, works correctly and looks like so:

int section_size = size / num_of_sections;
int last_section_size = size - ( section_size * (num_of_sections - 1) );

The only problem is that there are some combinations of size and num_of_sections that does not split very well. For example, if size = 10 and num_of_sections = 6, then the first four sections will be 1 element each, and the last section will be 6 elements.

How can I change this to an algorithm that will split it up more evenly, specifically, so that all sections are either size X or X+1? In the above example, the first four sections would be size 2, then the last two sections will be 1 each. There would obviously need to be a third variable produced that indicates a section number where all previous sections up to and including it are size X and all following are size X+1.

3
  • 4
    en.wikipedia.org/wiki/Bresenham%27s_line_algorithm Commented Oct 23, 2019 at 19:35
  • 2
    maybe try section[0] = size/n; section[1] = (size - section[0])/(n-1); section[2] = (size-section[0]-section[1])/(n-2); ... Commented Oct 23, 2019 at 19:38
  • 2
    (Both comments will produce the same result, but unless you need it to be very fast - which was the idea for the line drawing algorithm -, @pmg's is the simpler one to comprehend) Commented Oct 23, 2019 at 19:43

1 Answer 1

6

The usual approach, when you’re fine with grouping all the larger pieces, is

const int total=/*…*/,pieces=/*…*/;
const int base=total/pieces,extra=total%pieces;

Then the first extra (perhaps 0) pieces have size base+1 and the (pieces-extra) others have size base.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.