Code for the Advent of Code event
aoc
advent-of-code
1containers = {}
2
3parse = (line) -> containers[#containers + 1] = tonumber line
4
5copy_shallow = (tbl) -> {k, v for k, v in pairs tbl}
6
7combinations = (accum = 0, used = {}, target = 150) ->
8 counter = 0
9
10 for i = 1, #containers
11 continue if used[i] or accum + containers[i] > target
12
13 used[i] = true
14
15 if accum + containers[i] == target
16 counter += 1
17 else
18 copy = copy_shallow used
19 copy[i] = true
20 counter += combinations accum + containers[i], copy, target
21
22 counter
23
24counts = (accum = 0, results = {}, depth = 1, used = {}, target = 150) ->
25 for i = 1, #containers
26 continue if used[i] or accum + containers[i] > target
27
28 used[i] = true
29
30 if accum + containers[i] == target
31 results[#results + 1] = depth
32 else
33 copy = copy_shallow used
34 copy[i] = true
35 counts accum + containers[i], results, depth + 1, copy, target
36
37 -- Don't bother calculating minimum if we're not the root call
38 return unless depth == 1
39
40 min = results[1]
41 combination_count = 1
42 for i = 2, #results
43 if results[i] < min
44 min = results[i]
45 combination_count = 1
46 elseif results[i] == min
47 combination_count += 1
48
49 combination_count
50
51get_combinations = (target) ->
52 combinations 0, {}, target
53
54get_combinations_minimum = (target) ->
55 counts 0, {}, 1, {}, target
56
57{ :parse, :get_combinations, :get_combinations_minimum }