Skip to content

Instantly share code, notes, and snippets.

@conradfr
Last active February 20, 2020 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conradfr/f015173a0f0efabe9bd401b9eace5ab0 to your computer and use it in GitHub Desktop.
Save conradfr/f015173a0f0efabe9bd401b9eace5ab0 to your computer and use it in GitHub Desktop.
Benchmarking /r/elixir/comments/f4z9gn/evenodd_indexes/
defmodule Aseigo do
def split_even_odd_index(list) do
split_even_odd_index(list, true, {[], []})
end
defp split_even_odd_index([], _even_odd, result), do: result
defp split_even_odd_index([head | tail], true, {evens, odds}) do
split_even_odd_index(tail, false, {[head | evens], odds})
end
defp split_even_odd_index([head | tail], false, {evens, odds}) do
split_even_odd_index(tail, true, {evens, [head | odds]})
end
end
Benchee.run(
%{
"conrad" => fn list ->
result_odd_index = Enum.drop_every(list, 2)
{list -- result_odd_index, result_odd_index}
end,
"newking34_v1" => fn list ->
list
|> Stream.with_index()
|> Enum.reduce([[], []], fn {x, i}, [evens, odds] ->
case rem(i, 2) do
0 -> [evens ++ [x], odds]
_ -> [evens, odds ++ [x]]
end
end)
end,
"newking34_v2" => fn list ->
%{even: even, odd: odd} =
list
|> Enum.with_index()
|> Enum.group_by(
fn
{_n, idx} when rem(idx, 2) == 0 -> :even
_ -> :odd
end,
fn {n, _idx} -> n end
)
end,
"aseigo" => fn list ->
Aseigo.split_even_odd_index(list)
end
},
inputs: %{
"scaled2good" => [99, 99, 99, 99, 99],
"generated" => Enum.to_list(1..10_000),
"duplicated" => [0, 1, 1, 2, 2, 3, 4, 5]
},
print: [fast_warning: false]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment