Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- defmodule Test do
- def calc(matrix) do
- pairs = matrix
- |> String.codepoints()
- |> Enum.with_index()
- |> Enum.filter(fn({x, _y}) -> x != "0" end)
- |> Enum.map(fn({x, y}) -> {String.to_integer(x), y} end)
- [ %{matrix: pairs, path: [], state: matrix} ]
- end
- def pre(stack) do
- [first|stack] = stack
- f = fn
- x, y when String.length(item[:state]) == 0 -> y ++ x
- x, y -> [x|y]
- end
- run(first)
- |> Enum.reduce(stack, fn(item , st) -> f.(item, st) end )
- end
- def run(pairs) do
- hor = pairs[:matrix]
- |> Enum.map(fn({x,y}) -> [{x,y} , next_step(pairs[:matrix], y, 1)] end)
- ver = pairs[:matrix]
- |> Enum.map(fn({x,y}) -> [{x,y} , next_step(pairs[:matrix], y , 4)] end)
- hor ++ ver
- |> Enum.filter( fn([_p , p2]) -> p2 != nil end )
- |> Enum.filter( fn([{x, _y},{x2, _y2}]) -> x == x2 || x + x2 == 10 end)
- |> Enum.map( fn(pair) -> update_matrix(pairs, pair) end)
- end
- def next_step(list , current , step ) do
- Enum.find(list , fn({_x1 , y1}) -> y1 - current > 0 && rem((y1 - current) , step) == 0 end)
- end
- def update_matrix(matrix , [p , p2]) do
- filtered = matrix[:matrix]
- |> Enum.filter( fn(item) -> item != p && item != p2 end )
- %{
- matrix: filtered,
- state: state(filtered),
- path: matrix[:path] ++ [[p,p2]]
- }
- end
- def state(matrix) do
- Enum.reduce(matrix, "", fn({x,y}, acc) -> acc <> String.duplicate("0", y - String.length(acc)) <> Integer.to_string(x) end)
- end
- def normalize(state) do
- Enum.map(state, fn(item) -> %{
- state: item[:state],
- path: Enum.map(item[:path] , fn([{_x, y}, {_x1, y1}]) -> {y, y1} end)
- } end)
- end
- end
- pairs = "820569954037"
- |> Test.calc()
- |> Test.pre()
- |> Test.pre()
- |> Test.pre()
- |> Test.pre()
- |> Test.pre()
- IO.inspect Test.normalize(pairs)
Add Comment
Please, Sign In to add comment