Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active December 2, 2023 08:35
Show Gist options
  • Save henrik/31b2a6e1d2ffd2371df6368561228de1 to your computer and use it in GitHub Desktop.
Save henrik/31b2a6e1d2ffd2371df6368561228de1 to your computer and use it in GitHub Desktop.
Advent of Code day 1 part 2
# The no-frills take.
words = %w[ one two three four five six seven eight nine ]
hash = words.flat_map.with_index(1) { |word, index| [ [ word, index ], [ index.to_s, index ] ] }.to_h
puts DATA.readlines.sum { |line|
_, first_digit = hash.min_by { |string, _| line.index(string) || 999 }
_, last_digit = hash.max_by { |string, _| line.rindex(string) || -1 }
first_digit * 10 + last_digit
}
__END__
Data goes here
# The regex take.
words = %w[ one two three four five six seven eight nine ]
hash = words.map.with_index(1).to_h { [ _1, _2.to_s ] }
re = /(?=(#{Regexp.union(words)}|\d))/
puts DATA.readlines.sum { |line|
digits = line.scan(re).flatten.map { hash.fetch(_1, _1) }
(digits.first + digits.last).to_i
}
__END__
Data goes here
# The "unkilled darlings" take.
# I love `succ` and that $var interpolation doesn't require curlies, but rarely indulge.
words = %w[ one two three four five six seven eight nine ]
puts DATA.readlines.sum { |line|
words.each { line.gsub!(_1) { "#$&#{words.index($&).succ}#$&" } }
line.scan(/\d/).then { _1[0] + _1[-1] }.then(&:to_i)
}
__END__
Data goes here
# The "what if `scan` could find the first and last digit" take.
words = %w[ one two three four five six seven eight nine ]
puts DATA.readlines.sum { |line|
words.each { line.gsub!(_1) { "#$&#{words.index($&).succ}#$&" } }
line.scan(/(?=(\d)).*(\d)/).join.to_i
}
__END__
Data goes here
# The one without `readlines`.
words = %w[ one two three four five six seven eight nine ]
data = DATA.read
words.each { data.gsub!(_1) { "#$&#{words.index($&).succ}#$&" } }
puts data.scan(/(?=(\d)).*(\d)/).sum { _1.join.to_i }
__END__
Data goes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment