From 28e35196f5d1214df7e429c01101586c27612ee3 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 11 Dec 2023 07:24:14 -0800 Subject: [PATCH] [2023][ruby][11.2] --- 2023/ruby/day_11.rb | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/2023/ruby/day_11.rb b/2023/ruby/day_11.rb index 6cb9397..0bad97d 100644 --- a/2023/ruby/day_11.rb +++ b/2023/ruby/day_11.rb @@ -1,13 +1,37 @@ -image = ARGF.read -image.gsub!(/^(\.+)$/m, "\\1\n\\1") -image = image.split("\n").map(&:chars).transpose.map(&:join).join("\n") -image.gsub!(/^(\.+)$/m, "\\1\n\\1") -image = image.split("\n").map(&:chars) - -galaxies = image.flat_map.with_index {|row, y| - row.filter_map.with_index {|elem, x| elem == ?# ? [y,x] : nil } -} +image = ARGF.readlines(chomp: true).map(&:chars) +empty_rows = image.filter_map.with_index {|row,y| row.all? { _1 == ?. } ? y : nil } +empty_cols = image.transpose.filter_map.with_index {|col,x| col.all? { _1 == ?. } ? x : nil } + +galaxies = [] +y = x = 0 +image.each.with_index do |row, yy| + x = 0 + row.each.with_index do |elem, xx| + galaxies << [y,x] if elem == ?# + x += 1 + x += 999_999 if empty_cols.include?(xx) + end + + y += 1 + y += 999_999 if empty_rows.include?(yy) +end p galaxies.combination(2).sum {|a, b| a.zip(b).sum { (_1 - _2).abs } } + +# original part one + +# image = ARGF.read +# image.gsub!(/^(\.+)$/m, "\\1\n\\1") +# image = image.split("\n").map(&:chars).transpose.map(&:join).join("\n") +# image.gsub!(/^(\.+)$/m, "\\1\n\\1") +# image = image.split("\n").map(&:chars) + +# galaxies = image.flat_map.with_index {|row, y| +# row.filter_map.with_index {|elem, x| elem == ?# ? [y,x] : nil } +# } + +# p galaxies.combination(2).sum {|a, b| +# a.zip(b).sum { (_1 - _2).abs } +# }