Skip to content

Instantly share code, notes, and snippets.

@danielpclark
Created December 31, 2014 22:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpclark/aa90153a882a875eafc2 to your computer and use it in GitHub Desktop.
Save danielpclark/aa90153a882a875eafc2 to your computer and use it in GitHub Desktop.
My first Tail Recursive Ruby script
# 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"]
@danielpclark
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment