Skip to content

Instantly share code, notes, and snippets.

@TomasBouda
Created May 23, 2019 09:09
Show Gist options
  • Save TomasBouda/a5ec81027fbfbe2ba4ec4ba61a098147 to your computer and use it in GitHub Desktop.
Save TomasBouda/a5ec81027fbfbe2ba4ec4ba61a098147 to your computer and use it in GitHub Desktop.
Divides amount equaly between array of amounts
private decimal[] DivideEqualy(decimal[] array, decimal amount)
{
if (array.Length == 1)
{
return new decimal[] { amount };
}
decimal sum = array.Sum();
var precalculated = array.Select(l => amount * l / sum);
var ints = new LinkedList<int>(precalculated.Select(l => (int)l).OrderByDescending(x => x));
var remaindersSum = (int)Math.Round(precalculated.Select(l => l - (int)l).Sum());
var intNode = ints.First;
while (remaindersSum > 0)
{
intNode.Value++;
remaindersSum--;
intNode = intNode.NextOrFirst();
}
return ints.Select(i => (decimal)i).ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment