Skip to content

Instantly share code, notes, and snippets.

@carlwiedemann
Created December 3, 2023 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlwiedemann/e90e32481a19d19ee8258ad8e07ce55b to your computer and use it in GitHub Desktop.
Save carlwiedemann/e90e32481a19d19ee8258ad8e07ce55b to your computer and use it in GitHub Desktop.
Advent of Code 2023 day001.rb
require_relative "main"
module Day001
INPUT = File.read('INPUT.txt')
lines = INPUT.to_lines
##########
# Part 1 #
##########
values = lines.map do |line|
digit_chars = line.gsub(/\D/, "").chars
[digit_chars.first, digit_chars.last].join.to_i
end
answer1 = values.sum
pp answer1
##########
# Part 2 #
##########
# What are the first and last positions of all words in the string?
get_positions = ->(words, string) do
positions = []
words.each.with_index do |word, i|
index_first = string.index(word)
if index_first
index_last = string.rindex(word)
positions.push([index_first, i])
positions.push([index_last, i])
end
end
positions
end
values = lines.map do |line|
word_positions = get_positions.call(%w[zero one two three four five six seven eight nine], line)
digit_positions = get_positions.call(%w[0 1 2 3 4 5 6 7 8 9], line)
sorted_positions = (word_positions + digit_positions).sort_by(&:first)
first_digit = sorted_positions.first.last
last_digit = sorted_positions.last.last
[first_digit, last_digit].join.to_i
end
answer2 = values.sum
pp answer2
#######################
# Part 2, alternative #
#######################
total = 0
lines.each do |line|
first_position = nil
first_value = nil
last_position = nil
last_value = nil
needles = %w[zero one two three four five six seven eight nine 0 1 2 3 4 5 6 7 8 9]
needles.each.with_index do |needle, index|
i = 0
j = 0
while i <= line.length
if j == needle.length
if first_position.nil? || i - needle.length < first_position
first_position = i - needle.length
first_value = index % 10
end
if last_position.nil? || i - needle.length > last_position
last_position = i - needle.length
last_value = index % 10
end
end
if line[i] == needle[j]
j += 1
elsif line[i] == needle[0]
j = 1
else
j = 0
end
i += 1
end
end
var = first_value * 10 + last_value
total += var
end
answer2 = total
pp answer2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment