Skip to content

Instantly share code, notes, and snippets.

Created June 7, 2017 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/b9e1f97b4367bf74886a8d2a252bb66e to your computer and use it in GitHub Desktop.
Save anonymous/b9e1f97b4367bf74886a8d2a252bb66e to your computer and use it in GitHub Desktop.
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