Created
May 23, 2019 09:09
-
-
Save TomasBouda/a5ec81027fbfbe2ba4ec4ba61a098147 to your computer and use it in GitHub Desktop.
Divides amount equaly between array of amounts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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