-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (97 loc) · 1.79 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
var containers []int
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
c, _ := strconv.Atoi(scanner.Text())
containers = append(containers, c)
}
fmt.Printf("Part 1: %d\n", part1(containers, 150))
fmt.Printf("Part 2: %d\n", part2(containers, 150))
}
func part1(containers []int, litres int) int {
var count int
for k := 1; k < len(containers); k++ {
combinations(containers, k, func(comb []int) bool {
var sum int
for _, c := range comb {
sum += c
}
if sum == litres {
count++
}
return true
})
}
return count
}
func part2(containers []int, litres int) int {
counts := make(map[int]int) // number of containers -> number of combinations
for k := 1; k < len(containers); k++ {
combinations(containers, k, func(comb []int) bool {
var sum int
for _, c := range comb {
sum += c
}
if sum == litres {
counts[len(comb)]++
}
return true
})
}
lowest := len(containers)
for num := range counts {
if num < lowest {
lowest = num
}
}
return counts[lowest]
}
// combinations picks k elements from s and calls f for each combination, until
// there are no more combinations or the given function returns false.
func combinations(s []int, k int, f func(comb []int) bool) {
cont := true
comb := make([]int, k)
var rec func(ss []int, cc []int)
rec = func(ss []int, cc []int) {
for n := 0; n <= len(ss)-len(cc) && cont; n++ {
cc[0] = ss[n]
if len(cc) > 1 {
rec(ss[n+1:], cc[1:])
} else {
cont = cont && f(comb)
}
}
}
rec(s, comb)
/*
Algorithm example
abcdef pick 3
^^^
^^ ^
^^ ^
^^ ^
^ ^^
^ ^ ^
^ ^ ^
^ ^^
^ ^ ^
^ ^^
^^^
^^ ^
^^ ^
^ ^^
^ ^ ^
^ ^^
^^^
^^ ^
^ ^^
^^^
*/
}