comparison day13.rb @ 20:fac484765bc9

Implement Day 13 mirror line finding Walking in a loop didn't work, but consecutive pairs give a great starting point. And there might even be a more Ruby-ish version of the WHILE loop using zip, reverse and array ranges.
author IBBoard <dev@ibboard.co.uk>
date Wed, 13 Dec 2023 20:32:13 +0000
parents
children
comparison
equal deleted inserted replaced
19:1e16a25a9553 20:fac484765bc9
1 #! /usr/bin/env ruby
2
3 if ARGV.length != 1
4 abort("Incorrect arguments - needs input file")
5 elsif not File.exist? (ARGV[0])
6 abort("File #{ARGV[0]} did not exist")
7 end
8
9 file = ARGV[0]
10
11 maps = File.open(file, "r").each_line().map(&:chomp).chunk_while {|before, after| before.length == after.length}.filter {|chunk| chunk != [""]}.map {|chunk| chunk.map{|row| row.each_char.to_a}}
12
13 def find_reflection(data)
14 candidate_start = data.each_cons(2).with_index.flat_map {|vals,idx| a,b = vals; a == b ? [idx] : []}
15 valid_starts = candidate_start.flat_map do |start|
16 pos = start
17 reflected = start + 1
18 match = true
19 while pos > 0 and reflected < data.length - 1
20 pos -= 1
21 reflected += 1
22 match = data[pos] == data[reflected]
23 break unless match
24 end
25 match ? [start + 1] : []
26 end
27 valid_starts[0]
28 end
29
30 puts maps.flat_map {|data| [find_reflection(data).to_i * 100, find_reflection(data.transpose()).to_i]}.sum