Last active
December 28, 2015 22:59
-
-
Save ryandotsmith/7575445 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ostruct' | |
require 'minitest/autorun' | |
class P | |
attr_reader :x, :y | |
def initialize(x,y) | |
@x, @y = x, y | |
end | |
end | |
module Computer | |
extend self | |
def same_components?(p1, p2) | |
p1.x == p2.x || p1.y == p2.y | |
end | |
def slope(p1, p2) | |
(p2.y - p1.y) / Float((p2.x - p1.x)) | |
end | |
def direction(p1, p2) | |
p2.y > p1.y ? :up : :down | |
end | |
def choose_rand(*directions) | |
directions[rand(2)].tap {|x| puts("choice=#{x}")} | |
end | |
def choose_neighbor(slope, direction) | |
puts("slope=#{slope} direction=#{direction}") | |
if direction == :up | |
return :up if slope < -1 || slope > 1 | |
return choose_rand(:up, :left) if slope == -1 | |
return :left if slope > -1 && slope < 0 | |
return choose_rand(:up, :right) if slope == 1 | |
return :right if slope > 0 && slope < 1 | |
else | |
return :down if slope < -1 || slope > 1 | |
return choose_rand(:down, :right) if slope == -1 | |
return :right if slope > -1 && slope < 0 | |
return choose_rand(:down, :left) if slope == 1 | |
return :left if slope > 0 && slope < 1 | |
end | |
end | |
def compute(p1, p2) | |
if !same_components?(p1, p2) | |
s = slope(p1, p2) | |
d = direction(p1, p2) | |
choose_neighbor(s, d).tap {|x| puts("neighbor=#{x}")} | |
end | |
end | |
end | |
class Test < Minitest::Test | |
def test_cases | |
p1, p2 = P.new(0,3), P.new(1,2) | |
assert_includes([:down, :right], Computer.compute(p1, p2)) | |
p1, p2 = P.new(0,2), P.new(1,3) | |
assert_includes([:up, :right], Computer.compute(p1, p2)) | |
p1, p2 = P.new(3,0), P.new(2,1) | |
assert_includes([:up, :left], Computer.compute(p1, p2)) | |
p1, p2 = P.new(2,1), P.new(3,0) | |
assert_includes([:down, :right], Computer.compute(p1, p2)) | |
p1, p2 = P.new(1,1), P.new(3,2) | |
assert_equal(:right, Computer.compute(p1, p2)) | |
p1, p2 = P.new(3,3), P.new(2,0) | |
assert_equal(:down, Computer.compute(p1, p2)) | |
p1, p2 = P.new(3,3), P.new(0,2) | |
assert_equal(:left, Computer.compute(p1, p2)) | |
p1, p2 = P.new(3,3), P.new(1,0) | |
assert_equal(:down, Computer.compute(p1, p2)) | |
p1, p2 = P.new(3,3), P.new(2,2) | |
assert_includes([:left, :down], Computer.compute(p1, p2)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment