簡體   English   中英

將對象分為N個相等的部分

[英]Dividing an object into N amount of equal parts

我有一個對象(它實際上是一個2D數組,但為簡單起見,我發現可以想象它是一個矩形很有用)。 矩形的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
   }

當我閱讀答案時,我可能會踢自己,但此刻我的大腦有些僵化! 非常感謝。

這應該可以解決問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM