1
exercism fetch go change

cases_test.go

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package change

// Source: exercism/problem-specifications
// Commit: 52cf1cf Add test for incorrect greedy algorithm
// Problem Specifications Version: 1.1.0

var testCases = []struct {
	description    string
	coins          []int
	target         int
	valid          bool  // true => no error, false => error expected
	expectedChange []int // when .valid == true, the expected change coins
}{
	{
		"single coin change",
		[]int{1, 5, 10, 25, 100},
		25,
		true,
		[]int{25},
	},
	{
		"multiple coin change",
		[]int{1, 5, 10, 25, 100},
		15,
		true,
		[]int{5, 10},
	},
	{
		"change with Lilliputian Coins",
		[]int{1, 4, 15, 20, 50},
		23,
		true,
		[]int{4, 4, 15},
	},
	{
		"change with Lower Elbonia Coins",
		[]int{1, 5, 10, 21, 25},
		63,
		true,
		[]int{21, 21, 21},
	},
	{
		"large target values",
		[]int{1, 2, 5, 10, 20, 50, 100},
		999,
		true,
		[]int{2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100},
	},
	{
		"possible change without unit coins available",
		[]int{2, 5, 10, 20, 50},
		21,
		true,
		[]int{2, 2, 2, 5, 10},
	},
	{
		"another possible change without unit coins available",
		[]int{4, 5},
		27,
		true,
		[]int{4, 4, 4, 5, 5, 5},
	},
	{
		"no coins make 0 change",
		[]int{1, 5, 10, 21, 25},
		0,
		true,
		[]int{},
	},
	{
		"error testing for change smaller than the smallest of coins",
		[]int{5, 10},
		3,
		false,
		[]int(nil),
	},
	{
		"error if no combination can add up to target",
		[]int{5, 10},
		94,
		false,
		[]int(nil),
	},
	{
		"cannot find negative change values",
		[]int{1, 2, 5},
		-5,
		false,
		[]int(nil),
	},
}

change_test.go

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
package change

import (
	"reflect"
	"testing"
)

func TestChange(t *testing.T) {
	for _, tc := range testCases {
		actual, err := Change(tc.coins, tc.target)
		if tc.valid {
			if err != nil {
				t.Fatalf("%s : Change(%v, %d): expected %v, got error %s",
					tc.description, tc.coins, tc.target, tc.expectedChange, err.Error())
			} else {
				if !reflect.DeepEqual(actual, tc.expectedChange) {
					t.Fatalf("%s : Change(%v, %d): expected %#v, actual %#v",
						tc.description, tc.coins, tc.target, tc.expectedChange, actual)
				} else {
					t.Logf("PASS: %s", tc.description)
				}
			}
		} else {
			if err == nil {
				t.Fatalf("%s : Change(%v, %d): expected error, got %v",
					tc.description, tc.coins, tc.target, actual)
			} else {
				t.Logf("PASS: %s", tc.description)
			}
		}
	}
}

func BenchmarkChange(b *testing.B) {
	for _, tc := range testCases {
		for i := 0; i < b.N; i++ {
			Change(tc.coins, tc.target)
		}
	}
}