[2024][ruby][15.2]

main
Alpha Chen 1 week ago
parent 65186bc05b
commit 40b917bc31
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,4 +1,6 @@
input = DATA.read.split("\n\n") input = DATA.read.gsub(
/[#O\.@]/, %w[ # ## O [] . .. @ @. ].each_slice(2).to_h
).split("\n\n")
map = {} map = {}
input.shift.split("\n").each.with_index do |row, y| input.shift.split("\n").each.with_index do |row, y|
@ -29,8 +31,21 @@ def push(map, pos, move)
case map.fetch(pospos, nil) case map.fetch(pospos, nil)
when ?# when ?#
raise Nope raise Nope
when ?O when ?[, ?]
push(map, pospos, move) case move
when ?<, ?>
push(map, pospos, move)
when ?^, ?v
a = pospos
dx = {?[ => 1, ?] => -1}.fetch(map.fetch(pospos))
b = a.zip([0, dx]).map { _1 + _2 }
push_two(map, a, b, move).reverse.uniq.each do |pos, pospos|
map[pospos] = map.fetch(pos)
map.delete(pos)
end
else
fail
end
when nil when nil
else else
fail fail
@ -42,6 +57,28 @@ def push(map, pos, move)
pospos pospos
end end
def push_two(map, a, b, move)
delta = DELTAS.fetch(move)
aa = a.zip(delta).map { _1 + _2 }
bb = b.zip(delta).map { _1 + _2 }
[[a, aa], [b, bb]].flat_map {|pos, pospos|
case map.fetch(pospos, nil)
when ?#
raise Nope
when ?[, ?]
a_ = pospos
dx = {?[ => 1, ?] => -1}.fetch(map.fetch(pospos))
b_ = a_.zip([0, dx]).map { _1 + _2 }
[[pos, pospos]] + push_two(map, a_, b_, move)
when nil
[[pos, pospos]]
else
fail
end
}
end
DELTAS = %w[ ^ v < > ].zip([[-1,0], [1,0], [0,-1], [0, 1]]).to_h DELTAS = %w[ ^ v < > ].zip([[-1,0], [1,0], [0,-1], [0, 1]]).to_h
movements = input.shift.gsub("\n", "").chars movements = input.shift.gsub("\n", "").chars
@ -52,15 +89,28 @@ movements.each do |move|
end end
end end
pp map.select { _2 == ?O }.sum {|(y,x),_| 100 * y + x } # pp map.select { _2 == ?O }.sum {|(y,x),_| 100 * y + x }
pp map.select { _2 == ?[ }.sum {|(y,x),_| 100 * y + x }
__END__ __END__
####### ##########
#...#.# #..O..O.O#
#.....# #......O.#
#..OO@# #.OO..O.O#
#..O..# #..O@..O.#
#.....# #O#..O...#
####### #O..O..O.#
#.OO.O.OO#
#....O...#
##########
<vv<<^^<<^^ <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^

Loading…
Cancel
Save