From 3782908dbbad497736d9b4a28028b168646cee37 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Thu, 8 Dec 2022 21:30:57 -0800 Subject: [PATCH] [2022][ruby][9.2] --- 2022/ruby/day_09.rb | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) 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