Created
December 3, 2012 02:39
-
-
Save peterkinmond/4192239 to your computer and use it in GitHub Desktop.
Adku hiring puzzle
This file contains hidden or 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
def find_unique_paths(x, y, visited_points) | |
if is_at_end_point?(x, y) | |
@total_paths += 1 # successful path | |
elsif !visited_points.include?([x, y]) | |
visited_points << [x, y] # unvisited point, add to path | |
find_unique_paths(x + 1, y, visited_points.clone) if x + 1 <= @MAX_X # right | |
find_unique_paths(x - 1, y, visited_points.clone) if x > 0 # left | |
find_unique_paths(x, y + 1, visited_points.clone) if y + 1 <= @MAX_Y # down | |
find_unique_paths(x, y - 1, visited_points.clone) if y > 0 # up | |
end | |
end | |
def is_at_end_point?(x, y) | |
[x, y] == [@MAX_X, @MAX_Y] | |
end | |
size_of_grid = ARGV[0].to_i | |
@total_paths = 0 | |
# convert size into index values | |
@MAX_X = @MAX_Y = size_of_grid - 1 | |
find_unique_paths(0, 0, []) | |
puts "Total number of unique paths for #{size_of_grid} x #{size_of_grid} grid is #{@total_paths}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment