Last active
May 11, 2017 01:10
-
-
Save BadBastion/31857ec548c28eeccad6a50c037b1724 to your computer and use it in GitHub Desktop.
Improved breadth first product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule BreadthFirst do | |
defp init_cursor(dimension) do (for _ <- 1..dimension, do: 0) end | |
defp increment_cursor(cursor, depth, max, carry) do | |
cursor | |
|>List.foldr( | |
{carry, false, []}, | |
fn elem, {carry, unique, acc} -> | |
case elem + carry do | |
^depth -> {1, unique, [0 | acc]} | |
^max -> {0, true , [max | acc]} | |
sum -> {0, unique, [sum | acc]} | |
end | |
end) | |
end | |
defp next_cursor(acc, cursor, depth, max, carry) do | |
case increment_cursor(cursor, depth, max, carry) do | |
{1, _unique, _cursor} -> | |
acc # carry out, so we have hit the max depth | |
{_carry, true, cursor} -> | |
next_cursor([cursor | acc], cursor, depth, max, 1) | |
{_carry, false, cursor} -> | |
next_cursor(acc, cursor, depth, max, max) # not unique, seen in lower depth | |
end | |
end | |
defp product_at_depth(dimension, 1) do [init_cursor(dimension)] end | |
defp product_at_depth(dimension, depth) do | |
max = depth-1 # the max value | |
next_cursor([], init_cursor(dimension), depth, max, max) | |
|> Enum.reverse | |
end | |
def product(dimension, depth) when dimension >= 1 and depth >= 1 do | |
for i <- 1..depth do product_at_depth(dimension, i) end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment