comparison day1b.rb @ 0:76cc43966538

Start https://adventofcode.com/2023/day/1 in Ruby Part B was nasty because it didn't explain how to handle overlapping numbers, which was occasionally important for the last number.
author IBBoard <dev@ibboard.co.uk>
date Fri, 01 Dec 2023 20:00:22 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:76cc43966538
1 #! /usr/bin/env ruby
2
3 if ARGV.length != 1
4 abort("Incorrect arguments - pass a single file")
5 elsif not File.exist? (ARGV[0])
6 abort ("File #{ARGV[0]} did not exist")
7 end
8
9 file = ARGV[0]
10 sum = 0
11
12 number_map = {
13 "one" => 1,
14 "two" => 2,
15 "three" => 3,
16 "four" => 4,
17 "five" => 5,
18 "six" => 6,
19 "seven" => 7,
20 "eight" => 8,
21 "nine" => 9
22 }
23
24 (1..9).each {|i| number_map[i.to_s] = i}
25
26 File.open(file, "r").each_line do |line|
27 pos = line.length
28 value_1 = 0
29 number_map.each do |k,v|
30 index = line.index(k)
31 if index and index < pos
32 value_1 = v
33 pos = index
34 end
35 end
36 pos = line.length
37 line.reverse!
38 value_2 = 0
39 number_map.each do |k,v|
40 index = line.index(k.reverse)
41 if index and index < pos
42 value_2 = v
43 pos = index
44 end
45 end
46 sum += (value_1 * 10) + value_2
47 end
48
49 puts sum