Last active
August 29, 2015 14:13
-
-
Save charles-l/39fa233a9ebf09e182ed to your computer and use it in GitHub Desktop.
LCS Algorithm Visualization
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
| require 'curses' | |
| include Curses | |
| str1 = "hello my name is jake" | |
| str2 = "mah name is greg" | |
| init_screen | |
| start_color | |
| crmode | |
| noecho | |
| def pp(a) | |
| setpos 0, 0 | |
| addstr a.inspect.gsub('"','').gsub('nil',' ').split('],').join("]\n") | |
| refresh | |
| end | |
| def psleep(a) | |
| sleep 0.05 | |
| pp a | |
| end | |
| def lcslen(a, b) | |
| c = Array.new(a.size + 2) { |i| Array.new(b.size + 1) { |i| 0 } } | |
| c[0][1..c[0].size] = b | |
| for i in 0..a.size | |
| c[i+1][0] = a[i] | |
| end | |
| for i in 1..a.size do | |
| for j in 1..b.size do | |
| o = c[i][j] | |
| c[i][j] = "_" | |
| psleep(c) | |
| c[i][j] = o | |
| if a[i] == b[j] | |
| if ((j-1 > 0) && (i-1 > 0)) | |
| c[i][j] = c[i-1][j-1] + 1 | |
| end | |
| else | |
| if (j-1 < 0 and i-1 < 0) | |
| c[i][j] = [c[i][j-1], c[i-1][j]].max | |
| end | |
| end | |
| end | |
| end | |
| pp c | |
| sleep 3 | |
| end | |
| lcslen(str1.split(''), str2.split('')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment