Hi there,
i am new to elixir, so i solved some stuff on codewars.
i ran into this kata: https://www.codewars.com/kata/twice-linear/
I tried to solve storing the u in a list, and learned linked list are not a good idea to solve that thing
I could not get it working with tuples. I will push the solutions to github asap.
My fastest solution is based on a map cache, that is still to slow, i.e.
dotest(1000000, 54381286) # ~ 6-7 seconds
dotest(100000, 2911582) # ~ 300 ms
I get a timeout after 30 of 100 random tests…
def dbl_linear(n) do
{_, un} = Enum.reduce(
1..n,
{%{0 => 1}, 1},
fn (i, {u, un}) ->
x = Integer.floor_div((un - 1), 2)
y = Integer.floor_div((un - 1), 3)
xx = binary(x, u, 0, i - 1)
yy = binary(y, u, 0, i - 1)
un = 1 + Kernel.min(2 * xx, 3 * yy)
u = Map.put(
u,
i,
un
)
{
u,
un
}
end
)
un
end
defp binary(0, _, _, _), do: 1
defp binary(_, cache, lb, ub) when ub - lb <= 1 do
%{^ub => un} = cache
un
end
defp binary(un, cache, lb, ub) do
mid = lb + (
(ub - lb)
>>> 1)
%{^mid => mid_v} = cache
if mid_v > un do
binary(un, cache, lb, mid)
else
binary(un, cache, mid, ub)
end
end