简体   繁体   中英

Dividing an object into N amount of equal parts

I have an object (it's actually a 2D array but for simplicity I've found it useful to imagine it's a rectangle). The rectangle is 40 units wide on its X axis. I need to be able to divide this rectangle on the X plane by N number of dividers and return the unit number that this divider falls on (ie the array index). So, if there were two dividers the results would be 10 and 30.

I have another array to hold the results which I initialize with the number of dividers. I'd like to populate this results array in a loop, something like

for (int i = 1; i <= numberOfDividers; i++)
   {
      resultsArray[i] = some calculation involving i, the rectangle size and the number of dividers rounded up to the nearest integer
   }

I'll probably kick myself when I read the answer but I'm having a bit of a brain freeze at the moment! Many thanks.

This should do the trick:

//This will return the integer dividers as evenly spaced out as possible.
public static IEnumerable<int> GetDividers(this int totalLength, int dividersCount)
{
    //Error cases
    if (dividersCount > totalLength)
        throw new ArgumentOutOfRangeException();

    //Get trivial cases out of the way.
    if (dividersCount <= 0)
    {
        yield break;
    }

    var partitionLength = totalLength / (dividersCount + 1); //n dividers means n+1 partitions.
    var partitionTotalError = totalLength % (dividersCount + 1); //Integer division will truncate so we need to evaluate the error so we can distribute it later on as evenly as possible.
    var counter = partitionLength;

    while (counter < totalLength)
    {
        yield return counter;
        var currentStep = partitionLength + (partitionTotalError-- > 0 ? 1 : 0); //distribute error in middle and last step.
        counter += currentStep;
    }            
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM