Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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