From c8a3a0074bdba9c1ac6500fdbebbad6527c1d5e5 Mon Sep 17 00:00:00 2001 From: Johnathon Slightham Date: Wed, 10 Jan 2024 00:45:16 -0500 Subject: [PATCH] Day 11 --- 2023/day11/p1.rb | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2023/day11/p2.rb | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 2023/day11/p1.rb create mode 100644 2023/day11/p2.rb diff --git a/2023/day11/p1.rb b/2023/day11/p1.rb new file mode 100644 index 0000000..41d2e72 --- /dev/null +++ b/2023/day11/p1.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +def build_space_arr(grid) + offset = [] + grid.each_with_index do |row, i| + offset << if row.include? '#' + if offset.empty? + 0 + else + offset[i - 1] + 1 + end + elsif offset.empty? + 1 + else + offset[i - 1] + 2 + end + end + offset +end + +res = 0 +grid = [] +File.foreach('./2023/day11/data') do |line| + grid << line.strip.split('') +end + +row_offset = build_space_arr grid +col_offset = build_space_arr grid.transpose + +found_galaxies = [] +grid.each_with_index do |row, r| + row.each_with_index do |char, c| + next unless char == '#' + + found_galaxies.each do |galaxy| + res += (row_offset[r] - galaxy[:x]).abs + (col_offset[c] - galaxy[:y]).abs + end + + found_galaxies << { + x: row_offset[r], + y: col_offset[c] + } + end +end + +puts res diff --git a/2023/day11/p2.rb b/2023/day11/p2.rb new file mode 100644 index 0000000..fa0a842 --- /dev/null +++ b/2023/day11/p2.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# This is actually identical to p1, except for the offset of + 1_000_000 which was previously + 2 + +def build_space_arr(grid) + offset = [] + grid.each_with_index do |row, i| + offset << if row.include? '#' + if offset.empty? + 0 + else + offset[i - 1] + 1 + end + elsif offset.empty? + 1 + else + offset[i - 1] + 1_000_000 + end + end + offset +end + +res = 0 +grid = [] +File.foreach('./2023/day11/data') do |line| + grid << line.strip.split('') +end + +row_offset = build_space_arr grid +col_offset = build_space_arr grid.transpose + +found_galaxies = [] +grid.each_with_index do |row, r| + row.each_with_index do |char, c| + next unless char == '#' + + found_galaxies.each do |galaxy| + res += (row_offset[r] - galaxy[:x]).abs + (col_offset[c] - galaxy[:y]).abs + end + + found_galaxies << { + x: row_offset[r], + y: col_offset[c] + } + end +end + +puts res