AoC2023/day01/solution.rb

41 lines
1.1 KiB
Ruby
Executable File

#!/usr/bin/env ruby
# This is unfinished and broken. IDK why it doesn't work, but it's a bad solution.
# Check ./stolen.rb for a better solution that I stole from Reddit.
require 'pry'
# Part 1
input = File.readlines("./input").map(&:strip)
p1 = input.map{|line| line.scan(/\d/).values_at(0,-1).join}
solution = p1.map(&:to_i).sum
puts "Part 1 Solution is: #{solution}"
# Part 2
def transform(s)
digit_map = {one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9}
first_word = 0
until first_word.nil?
first_word = digit_map.map{ |word, digit| [ word.to_s,s.index(word.to_s)]}.to_h.reject{ |_k, val| val.nil? }.min_by{|_x, digit| digit}
s.sub!(first_word[0], digit_map[first_word[0].to_sym].to_s) unless first_word.nil?
end
s
end
p2 = input.map do |line|
transform(line).scan(/\d/).values_at(0,-1).join
# oline = line.dup
# new_line = transform(line)
# values = new_line.scan(/\d/).values_at(0,-1)
# final = values.join
# pp "#{oline}, #{new_line}, #{values}, #{final}"
# gets
# final
end
# binding.pry
solution = p2.map(&:to_i).sum
puts "Part 2 Solution is: #{solution}"