Created
November 25, 2019 11:13
-
-
Save tastyminerals/724fc6f06653fd75ac4a7a2689fe5989 to your computer and use it in GitHub Desktop.
change-making problem in D (naive implementation)
This file contains hidden or 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
#!/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