-
-
Save Madao-3/caa6bc78d7876fd1917b69b3b0aad007 to your computer and use it in GitHub Desktop.
LCS Ruby
This file contains 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
chars = ('a'..'z').to_a | |
x = [] | |
y = [] | |
5.times {|char| x << chars[rand(26)]} | |
5.times {|char| y << chars[rand(26)]} | |
c = Array.new(x.size + 1){Array.new(y.size + 1, 0)} | |
b = Array.new(x.size + 1){Array.new(y.size + 1, 0)} | |
def LCS_length(x, y, c, b) | |
(1..x.size).each do |i| | |
(1..y.size).each do |j| | |
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 | |
end | |
end | |
def 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) | |
end | |
end | |
LCS_length(x, y, c, b) | |
Print_LCS(x, b, x.size, y.size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment