aoc2025/mark/day3/part1_prep_for_2.rb

68 lines
1.4 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)
total += calculate_joltage(int_array)
end
total
end
# @param [<integer>] bank
def calculate_joltage(bank)
joltage = ''
first_digit, first_pos = max_and_index_from_slice(bank, 1)
joltage += first_digit.to_s
sub_bank = bank.slice(first_pos + 1, bank.length)
second_digit, _ = max_and_index_from_slice(sub_bank, 0)
joltage += second_digit.to_s
joltage.to_i
end
private
# Get max and index from the first part of the array. Ignore the last `offset`
# number of digits.
# @param [<integer>] array
# @param [integer] offset
def max_and_index_from_slice(array, offset)
maximum = array.slice(0, array.length - offset).max
index = array.find_index(maximum)
[maximum, index]
end
end
if ARGV[0].nil? || ARGV[0].empty?
puts "Usage: ruby part2.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}"