day1 complete

master
Guido Schweizer 2023-12-01 10:00:04 +01:00
commit 28cacbd5d6
5 changed files with 1128 additions and 0 deletions

1000
day_1/data Normal file

File diff suppressed because it is too large Load Diff

19
day_1/impl.rb Normal file
View File

@ -0,0 +1,19 @@
#prepare the input which is a string containing new lines
def parse(input)
data = []
input.each_line do |line|
data << line.gsub(/[a-zA-Z]/,"").chomp
end
data
end
# result should a single string or integer
def calculate(data)
result = 0
data.each do |d|
d = d.chars.to_a
num = "#{d.first}"+"#{d.last}"
result += num.to_i
end
result
end

44
day_1/impl_2.rb Normal file
View File

@ -0,0 +1,44 @@
MAPPER = {
"8": "eight",
"7": "seven",
"3": "three",
"9": "nine",
"5": "five",
"4": "four",
"6": "six",
"2": "two",
"1": "one"
}
#prepare the input which is a string containing new lines
def parse(input)
data = []
input.each_line do |line|
data << line.chomp
end
data
end
def find_first_digit(line, reverse:false)
line.length.times do |i|
j = reverse ? line.length - 1 - i : i
return line[j] if line[j].to_i != 0
sub_line = line[j..-1]
MAPPER.each do |k,v|
return k if sub_line.start_with?(v)
end
end
end
# result should a single string or integer
def calculate(data)
result = 0
data.each_with_index do |d,i|
first = find_first_digit(d)
last = find_first_digit(d, reverse: true)
num = "#{first}"+"#{last}"
result += num.to_i
end
result
end

24
day_1/run.rb Normal file
View File

@ -0,0 +1,24 @@
if ARGV[0] == "2"
require_relative "impl_2"
else
require_relative "impl"
end
def print(result)
if result.is_a? Array
result.map! {|l| "#{l}\n" }
end
puts result
end
def run
puts "running your implementation"
input = File.new("day_1/data").read
data = parse(input)
result = calculate(data)
print(result)
end
run

41
day_1/test.rb Normal file
View File

@ -0,0 +1,41 @@
if ARGV[0] == "2"
require_relative "impl_2"
RESULT = 281
else
require_relative "impl"
RESULT = 142
end
INPUT = <<~IN
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
IN
INPUT_2 = <<~IN
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
IN
def test_example
input = ARGV[0] == "2" ? INPUT_2 : INPUT
parsed = parse(input)
result = calculate(parsed)
if result == RESULT
puts "Test successful. Now run with real input"
puts "ruby day_1/run.rb #{ARGV[0]}"
else
puts "Test failed"
puts "expected \"#{RESULT}\" got \"#{result}\""
end
end
test_example