comparison day8b.rb @ 11:a7fb64b48830

Implement Day 8 - node/map walking Cheated on part 2 by finding out that the routes loop and you need to do the lowest-common-multiple to get a VERY large number
author IBBoard <dev@ibboard.co.uk>
date Sat, 09 Dec 2023 16:37:20 +0000
parents
children
comparison
equal deleted inserted replaced
10:25dda3397797 11:a7fb64b48830
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 lines = File.open(file, "r").each_line(chomp: true)
12
13 steps = lines.first.each_char.to_a
14
15 node_lines = lines.drop(1).to_a
16
17 #first_node, _ = node_lines[0].split("=")
18 #first_node.strip!
19
20 nodes = node_lines.map {|line| node, rest = line.split("="); left, right = rest.split(","); [node.strip, {"L" => left.strip[1..-1], "R" => right.strip[0..-2]}]}.to_h
21
22 cur_nodes = nodes.keys.filter {|v| v[-1] == "A"}
23
24 step_counts = cur_nodes.map do |cur_node|
25 step_count = 0
26 step_cycle = steps.cycle
27 while cur_node[-1] != "Z"
28 step_count += 1
29 cur_node = nodes[cur_node][step_cycle.next]
30 end
31 step_count
32 end
33 puts step_counts.reduce(1, :lcm)