Hello guys,
I’m currently struggling on a problem that should be easy but does not come as it should.
I need to decode an integer and output a list of index having it’s bit set to 1.
I came up with a first recursive implementation:
def listOfIndexOf({key, _size}) do
listOfIndexOf(key, 0, [])
end
defp listOfIndexOf(key, index, acc) do
if key == 0 do
acc
else
val = key &&& 1
listOfIndexOf(key >>> 1, index + 1,
if(val == 1,
do: [index | acc],
else: acc))
end
end
as well as a second one base on reduce_while
def listOfIndexOf({key, size}) do
{_,_, ret} = Enum.reduce_while(1..size, {key, 0, []},
fn (_, {key, index, acc} = input) ->
if key == 0 do
{:halt, input}
else
val = key &&& 1
updateKey = key >>> 1
ret = if(val == 1, do: [index | acc], else: acc)
{:cont, {updateKey, index + 1, ret}}
end
end)
ret
end
(still not a functional expert so remarks welcomed :))
(I’ve been playing with guard also to avoid if)
Unfortunately, I would need some faster implementation, currently with a key of 50 000 bits the process time is around 30 - 40 ms.
Would you think of a faster way of decoding ?
Thanks
Fred