Skip to content

Instantly share code, notes, and snippets.

@oskimura
Created April 18, 2011 11:57
Show Gist options
  • Select an option

  • Save oskimura/925192 to your computer and use it in GitHub Desktop.

Select an option

Save oskimura/925192 to your computer and use it in GitHub Desktop.
module Lcs where
import Data.Array
makeTable xs ys = tbl
where
n = length xs
m = length ys
tbl :: Array (Int,Int) Integer
tbl = array ((0,0),(n,m)) [let x = if (xs!!(i-1)) == (ys!!(j-1)) then 1 else 0
in ((i,j), if i==0 || j==0 then 0 else
maximum [ tbl!(i-1, j-1) + x
, tbl!(i-1, j)
, tbl!(i, j-1)
] )
| (i,j) <- range((0,0),(n,m)) ]
printLcs lcs xs ys = reverse . printLcs' n $ m
where
n = length xs
m = length ys
printLcs' 0 _ = ""
printLcs' _ 0 = ""
printLcs' i j
| xs!!(i-1) == ys!!(j-1) = (xs!!(i-1)) : next
| otherwise = if lcs!(i-1,j) >= lcs!(i,j-1) then printLcs' (i-1) j else printLcs' i (j-1)
where next = printLcs' (i-1) (j-1)
lcs xs ys = printLcs (makeTable xs $ ys) xs ys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment