diff --git a/2022/ruby/day_09.rb b/2022/ruby/day_09.rb
index 15239d0..f6f5dbc 100644
--- a/2022/ruby/day_09.rb
+++ b/2022/ruby/day_09.rb
@@ -3,12 +3,12 @@ require "set"
motions = ARGF.read.scan(/([RLUD])\s+(\d+)/).map { [_1, _2.to_i] }
class Snake
- attr_reader :tail
-
def initialize
- @head, @tail = [0, 0], [0, 0]
+ @knots = Array.new(10) { [0, 0] }
end
+ def tail = @knots.last
+
def move!(dir)
delta = case dir
when ?L then [ 0, -1]
@@ -17,14 +17,15 @@ class Snake
when ?D then [-1, 0]
else fail dir.inspect
end
- @head = @head.zip(delta).map { _1 + _2 }
-
- delta = @head.zip(@tail).map { _1 - _2 }
- if delta.any? { _1.abs > 1 }
- if delta.any?(&:zero?)
- @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 }
+ @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 }
+ if delta.any? { _1.abs > 1 }
+ @knots[i+1] = tail.zip(delta.map { _1.clamp(-1, 1) }).map { _1 + _2 }
end
end
end