Another update from ingydotnet^djgoku
This commit is contained in:
parent
91df62d461
commit
948b86eafa
7604 changed files with 108452 additions and 22726 deletions
|
|
@ -0,0 +1,42 @@
|
|||
defmodule LCS do
|
||||
def lcs_length(s,t) do
|
||||
{l,_c} = lcs_length(s,t,Map.new)
|
||||
l
|
||||
end
|
||||
|
||||
defp lcs_length([],t,cache), do: {0,Dict.put(cache,{[],t},0)}
|
||||
defp lcs_length(s,[],cache), do: {0,Dict.put(cache,{s,[]},0)}
|
||||
defp lcs_length([h|st]=s,[h|tt]=t,cache) do
|
||||
{l,c} = lcs_length(st,tt,cache)
|
||||
{l+1,Dict.put(c,{s,t},l+1)}
|
||||
end
|
||||
defp lcs_length([_sh|st]=s,[_th|tt]=t,cache) do
|
||||
if Dict.has_key?(cache,{s,t}) do
|
||||
{Dict.get(cache,{s,t}),cache}
|
||||
else
|
||||
{l1,c1} = lcs_length(s,tt,cache)
|
||||
{l2,c2} = lcs_length(st,t,c1)
|
||||
l = Enum.max([l1,l2])
|
||||
{l,Dict.put(c2,{s,t},l)}
|
||||
end
|
||||
end
|
||||
|
||||
def lcs(s,t) do
|
||||
{_,c} = lcs_length(s,t,Map.new)
|
||||
lcs(s,t,c,[])
|
||||
end
|
||||
|
||||
defp lcs([],_,_,acc), do: Enum.reverse(acc)
|
||||
defp lcs(_,[],_,acc), do: Enum.reverse(acc)
|
||||
defp lcs([h|st],[h|tt],cache,acc), do: lcs(st,tt,cache,[h|acc])
|
||||
defp lcs([_sh|st]=s,[_th|tt]=t,cache,acc) do
|
||||
if Dict.get(cache,{s,tt}) > Dict.get(cache,{st,t}) do
|
||||
lcs(s,tt,cache,acc)
|
||||
else
|
||||
lcs(st,t,cache,acc)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
IO.puts LCS.lcs('thisisatest','testing123testing')
|
||||
IO.puts LCS.lcs('1234','1224533324')
|
||||
Loading…
Add table
Add a link
Reference in a new issue