diff --git a/2024/ruby/day_12.rb b/2024/ruby/day_12.rb index 4d53774..afecd1c 100644 --- a/2024/ruby/day_12.rb +++ b/2024/ruby/day_12.rb @@ -35,11 +35,46 @@ perimeter = ->(plot) { } pp plots - .map { [garden.fetch(_1.first), _1.size, perimeter[_1].size] } - .sum { _2 * _3 } + .map { [_1.size, perimeter[_1]] } + .sum { _1 * _2.length } + +sides = ->(plot) { + id = garden.fetch(plot.first) + rows = plot.group_by(&:first).values.flat_map {|row| + [-1, 1].flat_map {|dy| + row + .map {|y,x| [y+dy, x] } + .reject { garden.fetch(_1, nil) == id } + .map(&:last) + .sort + .chunk_while { _1 + 1 == _2 } + } + } + cols = plot.group_by(&:last).values.flat_map {|row| + [-1, 1].flat_map {|dx| + row + .map {|y,x| [y, x+dx] } + .reject { garden.fetch(_1, nil) == id } + .map(&:first) + .sort + .chunk_while { _1 + 1 == _2 } + } + } + rows + cols +} + +pp plots + .map { [garden.fetch(_1.first), _1.size, sides[_1]] } + .sum { _2 * _3.sum(&:count) } __END__ -AAAA -BBCD -BBCC -EEEC +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE