将对象划分为N个相等的部分

时间:2016-06-23 09:25:04

标签: c# arrays math

我有一个物体(它实际上是一个二维阵列,但为了简单起见,我发现想象它是一个矩形很有用)。矩形在X轴上宽40个单位。我需要能够在X平面上将这个矩形除以N个分频器,并返回该分频器所在的单位数(即数组索引)。因此,如果有两个分频器,结果将是10和30。

我有另一个数组来保存我用分频器数量初始化的结果。我想在循环中填充这个结果数组,比如

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
   }

当我读到答案时,我可能会踢自己,但此刻我的脑部有点冻结!非常感谢。

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

//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;
    }            
}