-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package day138 | ||
|
||
import "errors" | ||
|
||
var errNotPossible = errors.New("Can not make this value") | ||
|
||
// ErrNotPossible represents that making this currency with these | ||
// denominations is impossible. | ||
func ErrNotPossible() error { | ||
return errNotPossible | ||
} | ||
|
||
// MinCurrencyRequiredBrute returns the minimum number of currency | ||
// necessary to make the desired amount. | ||
func MinCurrencyRequiredBrute(amt int, denomCents []int) (int, error) { | ||
if amt < 0 { | ||
return 0, errNotPossible | ||
} else if amt == 0 { | ||
return 0, nil | ||
} | ||
min := int(^uint(0) >> 1) | ||
found := false | ||
for _, denom := range denomCents { | ||
if count, err := MinCurrencyRequiredBrute(amt-denom, denomCents); err == nil && count+1 < min { | ||
found = true | ||
min = count + 1 | ||
} | ||
} | ||
if found { | ||
return min, nil | ||
} | ||
return 0, errNotPossible | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package day138 | ||
|
||
import "testing" | ||
|
||
var testcases = []struct { | ||
denom []int | ||
n int | ||
expected int | ||
err error | ||
}{ | ||
{[]int{1, 5, 10, 25}, 16, 3, nil}, | ||
{[]int{25}, 16, 0, ErrNotPossible()}, | ||
} | ||
|
||
func TestMinCurrencyRequiredBrute(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result, err := MinCurrencyRequiredBrute(tc.n, tc.denom); err != tc.err || result != tc.expected { | ||
t.Errorf("Expected (%v,%v) got (%v,%v)", tc.expected, tc.err, result, err) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkMinCurrencyRequiredBrute(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
MinCurrencyRequiredBrute(tc.n, tc.denom) | ||
} | ||
} | ||
} |