Longest Common subsequence, LCs, dynamic planning implementation.
# Encoding: UTF-8 # Author: Xu Jin, 4100213 # Date: nov 01,201 2 # longest-commom-subsequence # To find a longest commom subsequence 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 bchars = ("".. "E "). to_ax, y = [], [] 1. upto (RAND (5) + 5) {| I | x <chars [rand (chars. size-1)]} 1. upto (RAND (5) + 5) {| I | Y <chars [rand (chars. size-1)]} printf ("the random character arrays are: % s and % s \ n", x, y) C = array. new (X. size + 1) {array. new (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) do for j In (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 enddef print_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) endendlcs_length (X, Y, C, B) print "the longest-commom-subsequence is:" print_lcs (X, B, x. size, Y. size)