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"] |
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
Here are some optimizations I found while playing with your script:
You are likely already aware of this, though it may be worth adding to the gist for the benefit of other readers, but tail recursion is not enabled in the RubyVM by default and must be explicitly turned on:
You can read more about Tail Call Optimization in Ruby here. I didn't find enabling tail call optimization to make a significant difference with the given sample data, though it certainly improved things much more than swapping
Kernel#Array
withArray#slice!
.I hope this helps!