From b16cc7dacb610a9c8a89230d1183387b36279aa9 Mon Sep 17 00:00:00 2001 From: Patrick Auernig Date: Tue, 2 Mar 2021 02:56:38 +0100 Subject: [PATCH] Add solution for 2015 day 17 part 1 --- 2015/day-17/inputs/puzzle.txt | 20 ++++++++++++++++ 2015/day-17/inputs/test.txt | 5 ++++ 2015/day-17/main.rb | 44 +++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 2015/day-17/inputs/puzzle.txt create mode 100644 2015/day-17/inputs/test.txt create mode 100755 2015/day-17/main.rb diff --git a/2015/day-17/inputs/puzzle.txt b/2015/day-17/inputs/puzzle.txt new file mode 100644 index 0000000..f796965 --- /dev/null +++ b/2015/day-17/inputs/puzzle.txt @@ -0,0 +1,20 @@ +11 +30 +47 +31 +32 +36 +3 +1 +5 +3 +32 +36 +15 +11 +46 +26 +28 +1 +19 +3 diff --git a/2015/day-17/inputs/test.txt b/2015/day-17/inputs/test.txt new file mode 100644 index 0000000..4f82c26 --- /dev/null +++ b/2015/day-17/inputs/test.txt @@ -0,0 +1,5 @@ +20 +5 +15 +10 +5 diff --git a/2015/day-17/main.rb b/2015/day-17/main.rb new file mode 100755 index 0000000..f576883 --- /dev/null +++ b/2015/day-17/main.rb @@ -0,0 +1,44 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "pathname" +require "set" + +Container = Struct.new(:id, :cap) + +# quite inefficient, probably needs a DP solution +def combinations(amount, containers, stack = [], results = Set[]) + stack_sum = stack.sum { |x| x.cap } + + if stack_sum > amount + return results + elsif stack_sum == amount + results.add(stack.dup) + return results + end + + return results if containers.empty? + + containers.each_with_index do |container, idx| + combinations(amount, containers[(idx+1)..], [*stack, container], results) + end + + combinations(amount, containers[1..], [], results) +end + +def main(amount, file_paths) + amount = amount.to_i + + file_paths.each do |file_path| + puts "Files: #{file_path}" + + containers = file_path.each_line.with_index.map { |x, i| Container.new(i, x.to_i) }.freeze + + result = combinations(amount, containers) + + solution1 = result.size + puts " Solution 1: #{solution1}" + end +end + +main(ARGV[0], ARGV[1..].map { |x| Pathname(x) })