Mercurial > repos > other > adventofcode2023
comparison day1.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 File.open(file, "r").each_line do |line| | |
12 match = /^[^0-9]*([0-9]).*?(([0-9])[^0-9]*)?$/.match(line) | |
13 if match | |
14 first_num = match[1].to_i | |
15 second_num = match[3].nil? ? first_num : match[3].to_i | |
16 sum += (first_num * 10) + second_num | |
17 end | |
18 end | |
19 | |
20 puts sum |