Longest public subsequence, LCS, dynamic programming implementation.
#encoding: Utf-8 #author: Xu Jin, 4100213 #date: Nov, #Longest-commom-subsequence #to find a longest commom subse Quence of two given character arrays by using LCS algorithm #example output: #The random character arrays are: ["B", "a", "C", "a", "a", "B", "D"] and ["A", "C", "A", "C", "a", "a", "B"] #The longest-commom-subsequence is:a c a a b chars = (" A ".." E "). To_a x, y = [], [] 1.upto (rand (5) + 5) {|i| x << Chars[rand (chars.size-1)]} 1.upto (rand (5) + 5) {|i| y <&l T Chars[rand (chars.size-1)]} printf ("The random character arrays are:%s and%s\n", X, y) c = array.new (X.size + 1) {ARRAY.N
EW (y.size + 1)} B = Array.new (x.size + 1) {array.new (y.size + 1)} def lcs_length (x, y, C, b) m, n = x.size, y.size (0..M). each{|i| c[i][0] = 0} (0..N). each{|j| C[0][j] = 0} for-I in (1..M) does for J-(1..N) do if (x[i-1) =
= y [j-1]) c[i][j] = c[i-1][j-1] + 1; B[I][J] = 0 else if (c[i-1][j] >= c[i][j-1]) c[i][j] = c[i-1][j] b[i][j] = 1 else c[i][j] = c[i][j-1] b[i][j] = 2 End-end-end def Prin T_lcs (x, B, I, J) return if (i = = 0 | | j = = 0) if (b[i][j] = = 0) Print_lcs (x, B, I-1, j-1) printf ("%c", x[i-1
] Elsif (b[i][j] = = 1) Print_lcs (x, B, I-1, J) Else Print_lcs (x, B, I, j-1) end lcs_length (x, y, C, b)
Print "The longest-commom-subsequence is:" Print_lcs (x, B, X.size, y.size)