2023 Day 1 in Ruby

This commit is contained in:
2023-12-01 20:03:52 -05:00
commit d00e27d271
11 changed files with 1101 additions and 0 deletions

0
2023/base/data Normal file
View File

5
2023/base/p1.rb Normal file
View File

@@ -0,0 +1,5 @@
res = 0
File.foreach("./2023/base/data") do |line|
end
puts res

5
2023/base/p2.rb Normal file
View File

@@ -0,0 +1,5 @@
res = 0
File.foreach("./2023/base/data") do |line|
end
puts res

1000
2023/day1/data Normal file

File diff suppressed because it is too large Load Diff

11
2023/day1/p1.rb Normal file
View File

@@ -0,0 +1,11 @@
res = 0
File.foreach("./2023/day1/data") do |line|
first_int = -1
last_int = -1
line.each_byte do |b|
first_int = b - 48 if first_int == -1 and b > 47 and b < 58
last_int = b - 48 if b > 47 and b < 58
end
res += first_int * 10 + last_int
end
puts res

39
2023/day1/p2.rb Normal file
View File

@@ -0,0 +1,39 @@
res = 0
numbers = %w[one two three four five six seven eight nine]
File.foreach("./2023/day1/data") do |line|
first_digit_index = 10000
first_digit = 0
last_digit_index = -1
last_digit = 0
(1..9).each do |int|
next if (line.index int.to_s).nil?
if (line.index int.to_s) < first_digit_index
first_digit_index = line.index int.to_s
first_digit = int
end
if (line.rindex int.to_s) > last_digit_index
last_digit_index = line.rindex int.to_s
last_digit = int
end
end
numbers.each_with_index do |int, index|
next if (line.rindex int).nil?
if (line.index int) < first_digit_index
first_digit_index = line.index int
first_digit = index + 1
end
if (line.rindex int) > last_digit_index
last_digit_index = line.rindex int
last_digit = index + 1
end
end
res += first_digit * 10 + last_digit
end
puts res