50 lines
1.1 KiB
Ruby
50 lines
1.1 KiB
Ruby
require 'debug'
|
|
|
|
module FileHandler
|
|
def self.read_lines(file_path)
|
|
File.readlines(file_path, chomp: true).map do |line|
|
|
yield(line)
|
|
end
|
|
end
|
|
|
|
def self.read_file(file_path)
|
|
File.read(file_path)
|
|
end
|
|
end
|
|
|
|
class JoltageCalculator
|
|
def initialize(file_path, debug: false)
|
|
@file_path = file_path
|
|
@debug = debug
|
|
end
|
|
|
|
def calculate_total_joltage
|
|
total = 0
|
|
FileHandler.read_lines(@file_path) do |line|
|
|
int_array = line.split('').map(&:to_i)
|
|
length = int_array.length
|
|
first_digit = int_array.slice(0, length - 1).max
|
|
first_pos = int_array.find_index(first_digit)
|
|
second_digit = int_array.slice(first_pos + 1, length).max
|
|
total += "#{first_digit}#{second_digit}".to_i
|
|
end
|
|
total
|
|
end
|
|
end
|
|
|
|
if ARGV[0].nil? || ARGV[0].empty?
|
|
puts "Usage: ruby part1.rb <file_name> [debug]"
|
|
exit 1
|
|
end
|
|
|
|
debug = (ARGV[1] == "debug")
|
|
calculator = JoltageCalculator.new(ARGV[0], debug:)
|
|
puts "The answer is: #{calculator.calculate_total_joltage}"
|
|
|
|
# The answer is: 17166
|
|
|
|
# real 0m0,256s
|
|
# user 0m0,207s
|
|
# sys 0m0,049s
|
|
|