Created
December 31, 2014 22:45
-
-
Save danielpclark/aa90153a882a875eafc2 to your computer and use it in GitHub Desktop.
My first Tail Recursive Ruby script
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
# Tail Recursive | |
# A to Z path finder | |
def path_finder(arr, n = nil) | |
arr = arr.dup | |
n ||= Array(arr.shift) | |
val = arr.shift | |
if n.last.last == val.first | |
path_finder(arr, n << val) | |
elsif arr.any? {|b| n.last.last == b.first} | |
path_finder(arr.push(val), n) | |
else | |
n | |
end | |
end | |
y = ["AB", "BC", "BZ", "DG", "AZ", "CG", "GZ", "DG", "DK", "AH", "EH"] | |
path_finder(y) | |
# => ["AB", "BC", "CG", "GZ"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like your
arr.dup unless n
. And the use of tail is nice.I wonder about possibly implementing more functionality with this method. For example all possible paths from A to Z, or shortest. Since "AZ" is one option that would be a simple test case to implement. But I wonder if that would be overkill for this.