require 'debug' # Generic FileHandler class FileHandler def initialize(file_path) @file_path = file_path end # Usage: # FileHandler.new('/path_to_file').read_lines do |line| # # process line # end def read_lines File.foreach(@file_path, chomp: true).map do |line| yield(line) end end # Usage: # file_content = FileHandler.new('/path_to_file').read_file( def read_file File.read(@file_path) end end class PuzzleSolver def initialize(file_handler, debug: false) @handler = file_handler @debug = debug end def debug(message) puts message if @debug end def print_debug(message) print message if @debug end def solve raise NotImplementedError, 'Please implement this method in subclasses.' end end class HomeworkSolver < PuzzleSolver def calculate(operator, int_array) int_array.reduce(operator) end def solve lines = @handler.read_file.split("\n") operator_line = lines[-1].split(' ').map(&:to_sym) number_lines = lines[0...-1].map(&:chars) start_indices = lines[-1].chars.map.with_index {|x, i| x == ' ' ? nil : i }.reject {|x| x.nil?} solutions = start_indices.map.with_index do |index, i| start = index final = (i < start_indices.length - 1) ? start_indices[i + 1] - 2 : number_lines[0].length - 1 operator = operator_line[i] numbers = number_lines.map {|x| x[start..final]} integers = [] total_nums = numbers[0].length curr_index = total_nums - 1 while curr_index >= 0 integers << numbers.map {|digits| digits[curr_index]}.join.to_i curr_index -= 1 end calculate(operator, integers) end solutions.sum end end if ARGV[0].nil? || ARGV[0].empty? puts "Usage: ruby #{__FILE__} [debug]" exit 1 end file_path = ARGV[0] debug = (ARGV[1] == "debug") file_handler = FileHandler.new(file_path) ## Puzzle-specific cls = HomeworkSolver ## puts "The answer is: #{cls.new(file_handler, debug:).solve}"