Skip to content

Instantly share code, notes, and snippets.

@tastyminerals
Created November 25, 2019 11:13
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 tastyminerals/724fc6f06653fd75ac4a7a2689fe5989 to your computer and use it in GitHub Desktop.
Save tastyminerals/724fc6f06653fd75ac4a7a2689fe5989 to your computer and use it in GitHub Desktop.
change-making problem in D (naive implementation)
#!/usr/bin/rdmd
import std.algorithm : cartesianProduct;
import std.array;
import std.container.rbtree : redBlackTree;
import std.stdio;
int minimum_coins(int target, in int[] denominations)
{
auto origSet = redBlackTree(target);
int[] emptyArr = [];
int k = 0;
while (!origSet.empty)
{
++k;
auto newSet = redBlackTree(emptyArr);
foreach (tup; cartesianProduct(origSet.array, denominations))
{
if (tup[0] == tup[1])
{
return k;
}
else if (tup[0] > tup[1])
{
newSet.insert(tup[0] - tup[1]);
}
else
continue;
}
origSet = newSet;
}
return -1;
}
void main()
{
auto x = minimum_coins(97, [11, 10, 1]);
writeln(x);
}
unittest
{
assert(minimum_coins(97, [11, 10, 1]) == 9);
assert(minimum_coins(13, [9, 5, 3, 1]) == 3);
writeln("passed!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment