RosettaCodeData/Task/Longest-common-subsequence/Elixir/longest-common-subsequence-2.elixir

41 lines
1.1 KiB
Text
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
defmodule LCS do
2016-12-05 22:15:40 +01:00
def lcs_length(s,t), do: lcs_length(s,t,Map.new) |> elem(0)
2015-11-18 06:14:39 +00:00
2016-12-05 22:15:40 +01:00
defp lcs_length([],t,cache), do: {0,Map.put(cache,{[],t},0)}
defp lcs_length(s,[],cache), do: {0,Map.put(cache,{s,[]},0)}
2015-11-18 06:14:39 +00:00
defp lcs_length([h|st]=s,[h|tt]=t,cache) do
{l,c} = lcs_length(st,tt,cache)
2016-12-05 22:15:40 +01:00
{l+1,Map.put(c,{s,t},l+1)}
2015-11-18 06:14:39 +00:00
end
defp lcs_length([_sh|st]=s,[_th|tt]=t,cache) do
2016-12-05 22:15:40 +01:00
if Map.has_key?(cache,{s,t}) do
{Map.get(cache,{s,t}),cache}
2015-11-18 06:14:39 +00:00
else
{l1,c1} = lcs_length(s,tt,cache)
{l2,c2} = lcs_length(st,t,c1)
2016-12-05 22:15:40 +01:00
l = max(l1,l2)
{l,Map.put(c2,{s,t},l)}
2015-11-18 06:14:39 +00:00
end
end
def lcs(s,t) do
2016-12-05 22:15:40 +01:00
{s,t} = {to_charlist(s),to_charlist(t)}
2015-11-18 06:14:39 +00:00
{_,c} = lcs_length(s,t,Map.new)
2016-12-05 22:15:40 +01:00
lcs(s,t,c,[]) |> to_string
2015-11-18 06:14:39 +00:00
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
2016-12-05 22:15:40 +01:00
if Map.get(cache,{s,tt}) > Map.get(cache,{st,t}) do
2015-11-18 06:14:39 +00:00
lcs(s,tt,cache,acc)
else
lcs(st,t,cache,acc)
end
end
end
2016-12-05 22:15:40 +01:00
IO.puts LCS.lcs("thisisatest","testing123testing")
IO.puts LCS.lcs("1234","1224533324")