[英]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.