Skip to content

Instantly share code, notes, and snippets.

@charles-l
Created January 19, 2015 01:15
Show Gist options
  • Save charles-l/f0d2db2ff7c52ed5a8de to your computer and use it in GitHub Desktop.
Save charles-l/f0d2db2ff7c52ed5a8de to your computer and use it in GitHub Desktop.
simple diffing in ruby
str1 = "hello my name is jake"
str2 = "mah name is greg"
def printdiff(c, x, y, i, j)
return if c.nil?
if i > 0 and j > 0 and x[i] == y[j]
printdiff(c,x,y,i-1,j-1)
puts " " + x[i] unless x[i].nil?
elsif j > 0 and (i == 0 or c[i][j-1] >= c[i-1][j])
printdiff(c,x,y,i,j-1)
puts "+ " + y[j] unless y[j].nil?
elsif i > 0 and (j == 0 or c[i][j-1] < c[i-1][j])
printdiff(c,x,y,i-1,j)
puts "- " + x[i] unless x[i].nil?
else
print ""
end
end
def lcslen(a, b)
c = Array.new(a.size + 2) { |i| Array.new(b.size + 1) { |i| 0 } }
i = 0
j = 0
for i in 1..a.size do
for j in 1..b.size do
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
printdiff(c, a, b, i, j)
end
c = lcslen(str1.split(''), str2.split(''))
printdiff(c, str1.split(''), str2.split(''), 1, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment