I am new to elixir and am trying to replicate some nested looping from F# and C++. In those languages I used mutable arrays and with Elixir I am trying to replicate a 5 level deep nested recursive call.
I have some code that gives me the same count but its considerably slower. Any suggestions on how I can write this with improved performance and even fewer lines of code would be appreciated.
The test function at the end is what i use to execute the recursion. On my Mac it takes about 900 milliseconds.
defmodule Demo.Recursion do
use Bitwise
def get_new_number(index, current_number, number_list), do: (Enum.at(number_list, index) ||| current_number)
def fifth_loop(number, start, counter, number_list) do
items = for e <- start ..counter, do: get_new_number(e, number, number_list)
items
end
def fourth_loop(number, start, fourth_count, fifth_count, number_list) do
items =
for d <- start ..fourth_count do
new_number = get_new_number(d, number, number_list)
fifth_loop(new_number, d + 1, fifth_count, number_list)
end
items
end
def third_loop(number, start, third_count, fourth_count, fifth_count, number_list) do
items =
for c <- start ..third_count do
new_number = get_new_number(c, number, number_list)
fourth_loop(new_number, c + 1, fourth_count, fifth_count, number_list )
end
items
end
def second_loop(number, start, second_count, third_count, fourth_count, fifth_count, number_list ) do
items =
for b <- start ..second_count do
new_number = get_new_number(b, number, number_list)
third_loop(new_number, b + 1, third_count, fourth_count, fifth_count, number_list)
end
items
end
def first_loop(first_count, second_count, third_count, fourth_count, fifth_count, number_list) do
items =
for a <- 0 .. first_count do
number = Enum.at(number_list, a)
second_loop(number, a + 1, second_count, third_count, fourth_count, fifth_count, number_list)
end
|> List.flatten
IO.inspect length(items)
end
def test_recursion() do
new_list = for i <- 1..48 do i end |> List.flatten
{time, res} = :timer.tc(fn -> first_loop(43, 44, 45, 46, 47, new_list) end)
time / 1000
end
end
Any help is appreciated.
Thanks,