Skip to content

Instantly share code, notes, and snippets.

@Jwsonic
Created September 26, 2019 19:02
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 Jwsonic/cc36f788cc9b1d41c8068b9ae6bd4837 to your computer and use it in GitHub Desktop.
Save Jwsonic/cc36f788cc9b1d41c8068b9ae6bd4837 to your computer and use it in GitHub Desktop.
Courses Algo Problem
defmodule Dag do
defstruct edges: %{}
def from_list(list) do
Enum.reduce(list, %Dag{}, fn [to, from], dag -> insert(dag, from, to) end)
end
def insert(%Dag{edges: edges}, from, to) do
nodes = Map.get(edges, from, [])
updated_edges = Map.put(edges, from, [to | nodes])
%Dag{edges: updated_edges}
end
def circular?(%Dag{edges: edges}) do
Enum.any?(edges, fn {start, _} -> circular_check(MapSet.new(), [start], edges) end)
end
def output(list) do
IO.inspect("Input: #{inspect(list)}")
list
|> Dag.from_list()
|> Dag.circular?()
|> (&IO.inspect("Output: #{!&1}")).()
end
defp circular_check(_seen, [], _edges) do
false
end
defp circular_check(seen, [next | rest], edges) do
MapSet.member?(seen, next) ||
circular_check(MapSet.put(seen, next), rest ++ Map.get(edges, next, []), edges)
end
end
Dag.output([[1, 0]])
Dag.output([[1, 0], [0, 1]])
Dag.output([[1, 0], [0, 2], [2, 3]])
Dag.output([[1, 0], [0, 2], [2, 3], [3, 4], [4, 5], [2, 3]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment