Skip to content

Instantly share code, notes, and snippets.

@niku
Last active June 17, 2018 14:47
Show Gist options
  • Save niku/ccda845bf3cdc8c65515b5e05eb6d490 to your computer and use it in GitHub Desktop.
Save niku/ccda845bf3cdc8c65515b5e05eb6d490 to your computer and use it in GitHub Desktop.
9a10
> Agent.start_link(fn -> 0 end, name: Result)
11,15c12,13
< try do
< walk(maze, x, y, %{}, 0)
< catch
< pt -> pt
< end
---
> walk(maze, x, y, %{}, 0)
> Agent.get(Result, &(&1))
26c24
< {_, ?G} -> throw(pt)
---
> {_, ?G} -> Agent.update(Result, &(Enum.max([&1, pt])))
defmodule Gumimaze do
def read() do
lines = "maze.txt" |> File.read!() |> String.trim() |> String.split("\n")
for {line, y} <- Enum.with_index(lines), {c, x} <- Enum.with_index(String.to_charlist(line)), into: %{} do
{{x, y}, c}
end
end
def solve(maze) do
Agent.start_link(fn -> 0 end, name: Result)
{x, y} = elem(Enum.find(maze, fn {_, v} -> v == ?S end), 0)
walk(maze, x, y, %{}, 0)
Agent.get(Result, &(&1))
end
defp walk(maze, x, y, walked, pt) do
walked = Map.put(walked, {x, y}, true)
for {x2, y2} <- [{x + 1, y}, {x, y + 1}, {x - 1, y}, {x, y - 1}] do
case {walked[{x2, y2}], maze[{x2, y2}]} do
{true, _} -> :walked
{_, ?W} -> :wall
{_, ?\s} -> walk(maze, x2, y2, walked, pt)
{_, ?1} -> walk(maze, x2, y2, walked, pt + 1)
{_, ?G} -> Agent.update(Result, &(Enum.max([&1, pt])))
end
end
end
end
Gumimaze.read() |> Gumimaze.solve() |> IO.puts() # => 6
9a10
> Agent.start_link(fn -> 0 end, name: Result)
11,15c12,13
< try do
< walk(maze, x, y, %{}, 0)
< catch
< pt -> pt
< end
---
> walk(maze, x, y, %{}, 0)
> Agent.get(Result, &(&1))
24,26c22,24
< {_, ?\s} -> walk(maze, x2, y2, walked, pt)
< {_, ?1} -> walk(maze, x2, y2, walked, pt + 1)
< {_, ?G} -> throw(pt)
---
> {_, ?\s} -> Task.async(fn -> walk(maze, x2, y2, walked, pt) end) |> Task.await
> {_, ?1} -> Task.async(fn -> walk(maze, x2, y2, walked, pt + 1) end) |> Task.await
> {_, ?G} -> Agent.update(Result, &(Enum.max([&1, pt])))
defmodule Gumimaze do
def read() do
lines = "maze.txt" |> File.read!() |> String.trim() |> String.split("\n")
for {line, y} <- Enum.with_index(lines), {c, x} <- Enum.with_index(String.to_charlist(line)), into: %{} do
{{x, y}, c}
end
end
def solve(maze) do
Agent.start_link(fn -> 0 end, name: Result)
{x, y} = elem(Enum.find(maze, fn {_, v} -> v == ?S end), 0)
walk(maze, x, y, %{}, 0)
Agent.get(Result, &(&1))
end
defp walk(maze, x, y, walked, pt) do
walked = Map.put(walked, {x, y}, true)
for {x2, y2} <- [{x + 1, y}, {x, y + 1}, {x - 1, y}, {x, y - 1}] do
case {walked[{x2, y2}], maze[{x2, y2}]} do
{true, _} -> :walked
{_, ?W} -> :wall
{_, ?\s} -> Task.async(fn -> walk(maze, x2, y2, walked, pt) end) |> Task.await
{_, ?1} -> Task.async(fn -> walk(maze, x2, y2, walked, pt + 1) end) |> Task.await
{_, ?G} -> Agent.update(Result, &(Enum.max([&1, pt])))
end
end
end
end
Gumimaze.read() |> Gumimaze.solve() |> IO.puts()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment