Skip to content

Instantly share code, notes, and snippets.

@kenmazaika
Last active January 10, 2019 00:12
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 kenmazaika/e8e25be3f0bc1db7ad9d to your computer and use it in GitHub Desktop.
Save kenmazaika/e8e25be3f0bc1db7ad9d to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
class ManhattanDistance
# given a distance, calculate all possible move
# possibilities a certain manhattan distance away
def self.touples(n)
return [] if n == 0
list = []
# build the list of all [x,y] pairs such that:
# * x is an integer
# * y is an integer
# * x + y = n
# list will then contain exactly all the elements EXACTLY n manhattan away
# add in all of self.touples(n-1)
end
# convert a touple (x,y array pair) into
# versions for each 4 quadrants of the square
def self.expand_touple(touple)
[
# x, y
# -x, y
# x, -y
# -x, -y
]
end
end
class TestManhattanDistance < Minitest::Test
require 'set' # set is nice because it will be equal even if order is mismatched
def test_md
expected = [
[0,1],
[1,0]
].to_set
assert_equal expected, ManhattanDistance.touples(1).to_set
expected = [
[0,1], [1,0], # everything that is manhattan distance of 1 away
[1,1], # up one, over one
[2, 0], # over two
[0, 2] # up two
].to_set
assert_equal expected, ManhattanDistance.touples(2).to_set
end
def test_expand_touple
touple = [1,1]
expected = [[1,1], [-1,1], [1,-1], [-1, -1]].to_set
assert_equal expected, ManhattanDistance.expand_touple(touple).to_set
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment