require 'debug' class RotationDecoder def initialize(file_path) @file_path = file_path @mapping = { 'L' => :-, 'R' => :+ } end def decode(debug: false) code = 0 current_num = 50 puts "The dial starts by pointing at #{current_num}" if debug File.readlines(@file_path, chomp: true).map do |line| next if line.nil? || line.empty? direction, *number_arr = line.split('') number = Integer(number_arr.join) full_rotations = number / 100 rest = number - full_rotations * 100 raw_num = current_num.send(@mapping[direction], rest) # include 100 since that does not pass *through* zero but becomes exactly zero. passes_zero = 0 if current_num != 0 passes_zero = (0 <= raw_num && raw_num <= 100) ? 0 : 1 end current_num = raw_num % 100 print "The dial is rotaded #{line} to point at #{current_num}" if debug print "; during this rotation, it points at 0 #{full_rotations + passes_zero} times" if debug && full_rotations + passes_zero > 0 print "\n" if debug code += full_rotations + passes_zero code += 1 if current_num == 0 end code end end if ARGV[0].nil? || ARGV[0].empty? puts "Usage: ruby part2.rb [debug]" exit 1 end debug = (ARGV[1] == "debug") rd = RotationDecoder.new(ARGV[0]) puts "The code is: #{rd.decode(debug:)}"