[2022][ruby][9.2]

pull/1/head
Alpha Chen 2 years ago
parent caaa3da525
commit 3782908dbb
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -3,12 +3,12 @@ require "set"
motions = ARGF.read.scan(/([RLUD])\s+(\d+)/).map { [_1, _2.to_i] } motions = ARGF.read.scan(/([RLUD])\s+(\d+)/).map { [_1, _2.to_i] }
class Snake class Snake
attr_reader :tail
def initialize def initialize
@head, @tail = [0, 0], [0, 0] @knots = Array.new(10) { [0, 0] }
end end
def tail = @knots.last
def move!(dir) def move!(dir)
delta = case dir delta = case dir
when ?L then [ 0, -1] when ?L then [ 0, -1]
@ -17,14 +17,15 @@ class Snake
when ?D then [-1, 0] when ?D then [-1, 0]
else fail dir.inspect else fail dir.inspect
end end
@head = @head.zip(delta).map { _1 + _2 } @knots[0] = @knots[0].zip(delta).map { _1 + _2 }
(0...@knots.size-1).each do |i|
head = @knots[i]
tail = @knots[i+1]
delta = @head.zip(@tail).map { _1 - _2 } delta = head.zip(tail).map { _1 - _2 }
if delta.any? { _1.abs > 1 } if delta.any? { _1.abs > 1 }
if delta.any?(&:zero?) @knots[i+1] = tail.zip(delta.map { _1.clamp(-1, 1) }).map { _1 + _2 }
@tail = @tail.zip(delta.map { _1.clamp(-1, 1) }).map { _1 + _2 }
else
@tail = @tail.zip(delta.map { _1.clamp(-1, 1) }).map { _1 + _2 }
end end
end end
end end

Loading…
Cancel
Save