forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminimum-coins.js
57 lines (48 loc) · 1.74 KB
/
minimum-coins.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Part of Cosmos by OpenGenus Foundation */
function minimumCoins(value, denominations) {
var result = [];
// Assuming denominations is sorted in descendig order
for(var i = 0; i < denominations.length; i++) {
var cur_denom = denominations[i];
while(cur_denom <= value) {
result.push(cur_denom);
value -= cur_denom;
}
}
return result;
}
Array.prototype.equals = function(other) {
if (!other || !(other instanceof Array)) {
return false;
}
if (this.length != other.length) {
return false;
}
for (var i = 0; i < this.length; i++) {
if (this[i] != other[i]) {
return false;
}
}
return true;
}
function test() {
scenarios = [
{value: 100, denoms: [50, 25, 10, 5, 1], result: [50, 50]},
{value: 101, denoms: [50, 25, 10, 5, 1], result: [50, 50, 1]},
{value: 77, denoms: [50, 25, 10, 5, 1], result: [50, 25, 1, 1]},
{value: 38, denoms: [50, 25, 10, 5, 1], result: [25, 10, 1, 1, 1]},
{value: 17, denoms: [50, 25, 10, 5, 1], result: [10, 5, 1, 1]},
{value: 3, denoms: [50, 25, 10, 5, 1], result: [1, 1, 1]},
{value: 191, denoms: [100, 50, 25, 10, 5, 1], result: [100, 50, 25, 10, 5, 1]}
];
scenarios.forEach(function(scenario) {
var actual = minimumCoins(scenario.value, scenario.denoms);
if (!scenario.result.equals(actual)) {
console.error("Test Failed: Value: " + scenario.value
+ ", Denominations: " + scenario.denoms
+ ", Expected Result: " + scenario.result
+ ", Actual Result: " + actual);
}
}, this);
}
test();