From 975834ce552464306ca82fbece4aae214915a5ed Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 10 Dec 2019 21:38:35 -0800 Subject: [PATCH] [2019][ruby][11.x] use trig --- 2019/ruby/day_11.rb | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/2019/ruby/day_11.rb b/2019/ruby/day_11.rb index 7accfe2..49cf6da 100644 --- a/2019/ruby/day_11.rb +++ b/2019/ruby/day_11.rb @@ -2,16 +2,17 @@ require "stringio" require_relative "computer" +include Math + panels = Hash.new {|h,k| h[k] = [0]} panels[[0, 0]] = [1] i_r, i_w = IO.pipe o_r, o_w = IO.pipe -Robot = Struct.new(:panel, :dir) +Robot = Struct.new(:panel, :rad) -dirs = %i[ up right down left ] -robot = Robot.new([0, 0], 0) +robot = Robot.new([0, 0], PI/2) t = Thread.new { loop do @@ -19,22 +20,11 @@ t = Thread.new { panels[robot.panel] << o_r.gets.to_i dir = o_r.gets.to_i + raise "unexpected direction: #{dir}" unless [0, 1].include?(dir) + + robot.rad += -(2*dir - 1) * (PI/2) - delta = case dir - when 0 then -1 - when 1 then 1 - else raise "unexpected direction: #{dir}" - end - robot.dir += delta - robot.dir %= dirs.size - dir = dirs.fetch(robot.dir) - - delta = case dir - when :up then [ 0, 1] - when :right then [ 1, 0] - when :down then [ 0, -1] - when :left then [-1, 0] - end + delta = [cos(robot.rad).to_i, sin(robot.rad).to_i] robot.panel = robot.panel.zip(delta).map(&:sum) end }