From 59cdbf724bbcccf4c96f57b295b876599aab588a Mon Sep 17 00:00:00 2001 From: Patrick Auernig Date: Tue, 2 Mar 2021 18:33:28 +0100 Subject: [PATCH] Add solution for 2015 day 17 part 2 --- 2015/day-17/.gitignore | 1 + 2015/day-17/main.rb | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 2015/day-17/.gitignore diff --git a/2015/day-17/.gitignore b/2015/day-17/.gitignore new file mode 100644 index 0000000..bbd4ef0 --- /dev/null +++ b/2015/day-17/.gitignore @@ -0,0 +1 @@ +*.rbdump diff --git a/2015/day-17/main.rb b/2015/day-17/main.rb index f576883..59a9137 100755 --- a/2015/day-17/main.rb +++ b/2015/day-17/main.rb @@ -6,6 +6,21 @@ require "set" Container = Struct.new(:id, :cap) +# dumps result of previous solution to avoid recomputing +def memo(file) + dump_path = "#{file.basename}.rbdump" + + if File.exist?(dump_path) + File.open(dump_path, "rb") { |df| Marshal.load(df) } + else + File.open(dump_path, "wb") do |dumpfile| + result = yield + dumpfile.write(Marshal.dump(result)) + result + end + end +end + # quite inefficient, probably needs a DP solution def combinations(amount, containers, stack = [], results = Set[]) stack_sum = stack.sum { |x| x.cap } @@ -34,10 +49,15 @@ def main(amount, file_paths) containers = file_path.each_line.with_index.map { |x, i| Container.new(i, x.to_i) }.freeze - result = combinations(amount, containers) + result = memo(file_path) { combinations(amount, containers) } solution1 = result.size puts " Solution 1: #{solution1}" + + solution2 = result.min_by { |x| x.size }.size + .then { |mincomb| result.select { |x| x.size == mincomb } } + .size + puts " Solution 2: #{solution2}" end end