Last active
July 8, 2022 21:17
-
-
Save coproduto/10c8139c5ed3a25cf6bf2d6cd2297ef2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule DoubleCola do | |
| @moduledoc """ | |
| Resolve o problema "Double Cola". | |
| Para encontrar a solução para o inteiro `n`, chame a função | |
| `DoubleCola.find_person_at_position/1`. | |
| """ | |
| @initial_queue_size 5 | |
| @names ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"] | |
| @doc """ | |
| Retorna o nome da pessoa na posição `n` | |
| """ | |
| @spec find_person_at_position(integer()) :: String.t() | |
| def find_person_at_position(n) do | |
| iteration = find_iteration(n) | |
| replications = trunc(:math.pow(2, iteration)) | |
| predecessors = @initial_queue_size * (replications - 1) | |
| person_index = div(n - predecessors, replications) | |
| Enum.at(@names, person_index) | |
| end | |
| @doc """ | |
| Descobre em qual iteração do processo de replicação da fila | |
| a posição `position` será produzida | |
| """ | |
| @spec find_iteration(integer()) :: integer() | |
| def find_iteration(position) do | |
| position | |
| |> Kernel./(@initial_queue_size) | |
| |> Kernel.+(1) | |
| |> :math.log2() | |
| |> floor() | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment