diff --git a/day_06/1.rb b/day_06/1.rb new file mode 100755 index 0000000..62361f9 --- /dev/null +++ b/day_06/1.rb @@ -0,0 +1,53 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +class Main + def run + problems = Hash.new(0) + $stdin.each_line do |line| + arr = line.chomp.split.map do |part| + if /^\d+$/.match?(part) + part.to_i + else + part.to_sym + end + end.compact + + arr.each_with_index do |part, idx| + problems[idx] = [] unless problems.key?(idx) + problems[idx] << part + end + end + + @sum = 0 + problems.each do |_, parts| + @sum += recurse(parts[..-2], parts.last) + end + + puts @sum + end + + def recurse(nums, op) + return nums.first if nums.size == 1 + + num1, num2 = nums.shift(2) + + case op + when :+ + nums.unshift(num1 + num2) + when :- + nums.unshift(num1 - num2) + when :* + nums.unshift(num1 * num2) + when :/ + if nums[1] == 0 + raise "Division by zero" + end + nums.unshift(num1 / num2) + end + + recurse(nums, op) + end +end + +Main.new.run diff --git a/day_06/2.rb b/day_06/2.rb new file mode 100755 index 0000000..ecae48f --- /dev/null +++ b/day_06/2.rb @@ -0,0 +1,68 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "stringio" + +class Main + def run + num_map = [] + $stdin.each_line do |line| + num_map << line.chomp.chars + end + + problems = Hash.new(0) + count = 0 + problems[count] = Hash.new(0) + + num_map.transpose.each do |chars| + if chars.uniq == [" "] + count += 1 + problems[count] = Hash.new(0) + next + end + + num_str = StringIO.new + chars.each do |ch| + if ch.match?(/\d/) + num_str.write(ch) + else + problems[count][:op] = [] unless problems[count].key?(:op) + problems[count][:op] << ch.to_sym unless ch == " " + end + end + problems[count][:nums] = [] unless problems[count].key?(:nums) + problems[count][:nums] << num_str.string.to_i unless num_str.string.empty? + end + + @sum = 0 + problems.each do |_, data| + @sum += recurse(data[:nums], data[:op].first) + end + + puts @sum + end + + def recurse(nums, op) + return nums.first if nums.size == 1 + + num1, num2 = nums.shift(2) + + case op.to_sym + when :+ + nums.unshift(num1 + num2) + when :- + nums.unshift(num1 - num2) + when :* + nums.unshift(num1 * num2) + when :/ + if nums[1] == 0 + raise "Division by zero" + end + nums.unshift(num1 / num2) + end + + recurse(nums, op) + end +end + +Main.new.run