Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Last active December 28, 2015 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryandotsmith/7575445 to your computer and use it in GitHub Desktop.
Save ryandotsmith/7575445 to your computer and use it in GitHub Desktop.
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