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 } }