Last active
May 10, 2017 22:33
-
-
Save BadBastion/52d80c7136ea51fc5626d99ea9a90f62 to your computer and use it in GitHub Desktop.
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 T do | |
defp init_cursor(dimension) do (for _ <- 1..dimension, do: 0) end | |
defp increment_cursor(cursor, depth) do | |
max = depth-1 | |
cursor | |
|>List.foldr( | |
{1, 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) do | |
case increment_cursor(cursor, depth) do | |
{1, _unique, _cursor} -> acc # carry out, so we have hit the max depth | |
{_carry, true, cursor} -> next_cursor([cursor | acc], cursor, depth) | |
{_carry, false, cursor} -> next_cursor(acc, cursor, depth) # 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 | |
next_cursor([], init_cursor(dimension), depth) | |
|> 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