Skip to content

Instantly share code, notes, and snippets.

@Madao-3
Created March 6, 2017 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Madao-3/caa6bc78d7876fd1917b69b3b0aad007 to your computer and use it in GitHub Desktop.
Save Madao-3/caa6bc78d7876fd1917b69b3b0aad007 to your computer and use it in GitHub Desktop.
LCS Ruby
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