Created
September 18, 2012 03:33
-
-
Save davidchambers/3741090 to your computer and use it in GitHub Desktop.
Problem: Determine all the paths for a given node.
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
# Problem: Determine all the paths for a given node. | |
# | |
# A | |
# / \ | |
# / \ | |
# B C | |
# / \ \ | |
# / \ \ | |
# C D D | |
# \ | |
# \ | |
# D | |
A = name: 'A', parents: [] | |
B = name: 'B', parents: [A] | |
C = name: 'C', parents: [A,B] | |
D = name: 'D', parents: [B,C] | |
paths = ({name, parents}, memo = [], results = []) -> | |
memo = [name, memo...] | |
if parents.length | |
paths parent, memo, results for parent in parents | |
else | |
results.push memo | |
results | |
# > console.log paths A | |
# [ [ 'A' ] ] | |
# > console.log paths B | |
# [ [ 'A', 'B' ] ] | |
# > console.log paths C | |
# [ [ 'A', 'C' ], [ 'A', 'B', 'C' ] ] | |
# > console.log paths D | |
# [ [ 'A', 'B', 'D' ], [ 'A', 'C', 'D' ], [ 'A', 'B', 'C', 'D' ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!