Skip to content

Instantly share code, notes, and snippets.

@themaxhero
Last active November 3, 2021 10:42
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 themaxhero/60894c89c15ff0615256b7272c4ca134 to your computer and use it in GitHub Desktop.
Save themaxhero/60894c89c15ff0615256b7272c4ca134 to your computer and use it in GitHub Desktop.
Resolution for Double Cola Problem in Elixir
defmodule DoubleCola do
defp mapper({current_names, size}),
do: Enum.map(current_names, &(%{name: &1, size: size}))
defp traverse([%{name: name, size: size} | rest], n) when n <= size,
do: name
defp traverse([%{name: name, size: size} | rest], n),
do: traverse(rest, n - size)
def find_nth(names, n) do
names_length = length(names)
range = Stream.unfold(1, &({&1, &1 * 2}))
names
|> Stream.cycle()
|> Stream.chunk_every(names_length)
|> Stream.zip(range)
|> Stream.flat_map(&mapper/1)
|> Enum.take(n)
|> traverse(n)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment