From d5f41153b771551b620b8a039be33f93bf427bf3 Mon Sep 17 00:00:00 2001 From: Johnathon Slightham Date: Fri, 8 Dec 2023 01:45:52 -0500 Subject: [PATCH] Day 8 --- 2023/day8/p1.rb | 26 ++++++++++++++++++++++++++ 2023/day8/p2.rb | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 2023/day8/p1.rb create mode 100644 2023/day8/p2.rb diff --git a/2023/day8/p1.rb b/2023/day8/p1.rb new file mode 100644 index 0000000..400cb20 --- /dev/null +++ b/2023/day8/p1.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +f = File.open('./2023/day8/data') +directions = f.readline.strip.split('') + +graph = {} +f.each_line do |line| + line.strip! + next if line.empty? + + graph[line.split(' ')[0]] = line.split('(')[1].split(')')[0].split(', ') +end + +i = 0 +res = 0 +cur_pos = 'AAA' +while cur_pos != 'ZZZ' + i = 0 if i == directions.length + + cur_pos = graph[cur_pos][0] if directions[i] == 'L' + cur_pos = graph[cur_pos][1] if directions[i] == 'R' + i += 1 + res += 1 +end + +puts res diff --git a/2023/day8/p2.rb b/2023/day8/p2.rb new file mode 100644 index 0000000..0b7a927 --- /dev/null +++ b/2023/day8/p2.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +f = File.open('./2023/day8/data') +directions = f.readline.strip.split('') + +starting_vertices = [] +graph = {} +f.each_line do |line| + line.strip! + next if line.empty? + + vertex_label = line.split(' ')[0] + graph[vertex_label] = line.split('(')[1].split(')')[0].split(', ') + starting_vertices << vertex_label if vertex_label.end_with? 'A' +end + +res = -1 +starting_vertices.each do |vertex| + i = 0 + curr_length = 0 + cur_pos = vertex + until cur_pos.end_with? 'Z' + i = 0 if i == directions.length + + cur_pos = graph[cur_pos][0] if directions[i] == 'L' + cur_pos = graph[cur_pos][1] if directions[i] == 'R' + i += 1 + curr_length += 1 + end + res = if res == -1 + curr_length + else + res.lcm(curr_length) + end +end + +puts res