Created
May 17, 2016 13:30
-
-
Save jvmvik/7e2f98d67ea8963fa8340e2f2478095c to your computer and use it in GitHub Desktop.
Solve a simple dependency graph in Ruby. This is useful to follow file dependency like: #include in C++
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
| # Walk a dependency graph | |
| # | |
| def walk(deps, available = []) | |
| # End condition | |
| return if deps.keys.size == available.size | |
| if available.size == 0 | |
| deps.each do |f, h| | |
| next if h[:visited] == true | |
| next if h[:includes].size > 0 | |
| deps[f][:visited] = true | |
| available << f | |
| puts "-> #{f}" | |
| end | |
| end | |
| deps.each do |f,h| | |
| next if h[:visited] == true | |
| next unless h[:includes].all? { |inc| available.index(inc) } | |
| deps[f][:visited] = true | |
| available << f | |
| puts "-> #{f}" | |
| end | |
| walk(deps, available) | |
| end | |
| # Dependency graph | |
| deps = { | |
| 'A' => { | |
| :includes => ['B','C'], # Dependency | |
| :visited => false # Mark node visited | |
| }, | |
| 'B' => { | |
| :includes => ['C'], | |
| :visited => false | |
| }, | |
| 'C' => { | |
| :includes => [], | |
| :visited => false | |
| } | |
| } | |
| # Start walking | |
| walk(deps, []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment