Created
June 7, 2017 16:24
-
-
Save anonymous/b9e1f97b4367bf74886a8d2a252bb66e to your computer and use it in GitHub Desktop.
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
void Main() | |
{ | |
for (int i = 0; i < 1000; i++) | |
{ | |
foreach(var b in ValueToUsableTokens(5000000, ValidMoney)) {} | |
//Bruno's implementation | |
//foreach(var b in GetDecimalQuantities(5000000)) {} | |
} | |
} | |
private static readonly decimal[] ValidMoney = | |
new[]{50M, 20M, 10M, 5M, 2M, 1M, 0.5M, 0.2M, 0.1M, 0.05M, 0.02M, 0.01M}; | |
public IEnumerable<KeyValuePair<decimal, int>> GetDecimalQuantities(decimal value) | |
{ | |
int count; | |
foreach(decimal note in ValidMoney) | |
{ | |
count = 0; | |
while(value >= note) | |
{ | |
count++; | |
value -= note; | |
} | |
if(count > 0) | |
{ | |
yield return new KeyValuePair<decimal, int>(note, count); | |
} | |
if (value == 0) | |
break; | |
} | |
} | |
public static IEnumerable<KeyValuePair<decimal, int>> ValueToUsableTokens(decimal value, params decimal[] tokens){ | |
for(var i = 0; i < tokens.Length; ++i){ | |
var quotient = (int)(value / tokens[i]); | |
if(quotient > 0){ | |
yield return new KeyValuePair<decimal, int>(tokens[i], quotient); | |
} | |
value = value - quotient * tokens[i]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment