fireproofsocks
I worked out some code for a little interview-type puzzle question that requires one to implement code to solve a “Rock Paper Scissors” tournament. The task was to write a function that would accept a string of letters consisting of R, P, and S’s (denoting Rock, Paper, or Scissors) and return the letter of the winner or “None” if nobody won.
The rules are as follows:
- For each round, the 1st “player” (i.e. letter) competes with the 2nd, the 3rd with the 4th, the 5th with the 6th, and so on.
- If there’s an odd number of players, the odd-man-out advances to the next round
- If there’s a tie (e.g. RR), both are eliminated and do not advance to the next round.
- Keep advancing through rounds until there is one winner or return “None”.
I came up with code that meets the spec:
defmodule RockPaperScissors do
def find_winner(lineup) do
case _find_winner(String.codepoints(lineup), []) do
"" -> "None"
result -> result
end
end
# Nobody won
defp _find_winner([], []), do: ""
# Cases where only 1 player is left means we're done!
defp _find_winner([one_remaining], []), do: one_remaining
# Single player remaining (bc of odd number of players)
defp _find_winner([one_remaining], acc), do: _find_winner([], acc ++ [one_remaining])
# Advance to the next round!
defp _find_winner([], acc), do: _find_winner(acc, [])
defp _find_winner(["R", "R" | rest], acc), do: _find_winner(rest, acc)
defp _find_winner(["R", "P" | rest], acc), do: _find_winner(rest, acc ++ ["P"])
defp _find_winner(["R", "S" | rest], acc), do: _find_winner(rest, acc ++ ["R"])
defp _find_winner(["P", "R" | rest], acc), do: _find_winner(rest, acc ++ ["P"])
defp _find_winner(["P", "P" | rest], acc), do: _find_winner(rest, acc)
defp _find_winner(["P", "S" | rest], acc), do: _find_winner(rest, acc ++ ["S"])
defp _find_winner(["S", "R" | rest], acc), do: _find_winner(rest, acc ++ ["R"])
defp _find_winner(["S", "P" | rest], acc), do: _find_winner(rest, acc ++ ["S"])
defp _find_winner(["S", "S" | rest], acc), do: _find_winner(rest, acc)
end
For clarity, here are a few test cases:
assert RockPaperScissors.find_winner("R") == "R"
assert RockPaperScissors.find_winner("RR") == "None"
assert RockPaperScissors.find_winner("RRS") == "S"
assert RockPaperScissors.find_winner("RRRSRSPS") == "S"
This solution works, but I’m wondering about optimizations to this… appending to a list is expensive, but because the order of the players is important, prepending won’t work. So this ends up being O(n) complexity I think. I’m wondering if there are other ways to tackle this – using folding or captures or passing anonymous functions that would be more efficient so execution can happen more efficiently.
Any thoughts?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
NobbZ
Looks like a nice puzzle. Do you have some example inputs and their expected outputs to test against?
Edit, ok I’m stupid and blind at the same time
stefanluptak
It’s quite easy to use prepending in this case. (if I am not mistaken) Just reverse the
accwhen advancing to the next round. I tried it and the results are very nice. I generated three inputs to benchmark on. 10 chars long, 1_000 chars long, 100_000 chars long. I tried 1_000_000 too, but that was taking extremely long.Generating inputs:
Code:
Benchmark:
Results:
I am sure, there are some other improvements to be made, but this was the lowest hanging fruit in my opinion. I am looking forward to other suggestions.
NobbZ
After I had to wait for my BEAM to crash because of infinite recursion (it blocked my laptop totally, even ssh was impossible) I rewrote to use binaries.
The BEAM can optimise appending on them under certain conditions, and I think I have met them.
Also this way you do not need to create that extra list that holds the code points.
A next step was to remove the
case/2from the public function and let this be handled by the helper function.Then I combined the “draws” into a single pattern match, in your version it would be
defp _find_winner([x, x|rest], acc), do: _find_winner(rest, acc).After that I extracted another function which would determine the winner of a single match.
And the last thing I did, was to remove the underscore prefix, because I do read it as “this isn’t meant to be used”.
I have not benchmark this or one of your codes. But I have not really optimzed for speed, but instead rewritten in a way that I consider easier to read and maintain.
stefanluptak
FYI, here’s the comparison to my and to original solution for 100_000 chars:
krstfk
I think this would be correct, and it gets rid of appending (but not of the String.codepoints call), and it’s fairly simple :
Edit → I had not read Nobbz solution, the general idea seems close, but matching directly on binaries is indeed better.
krstfk
I decided to test things with the previous solution, but matching binaries directly :
I believe it is still correct, but much faster and I think still readable. Running the benchmarks provided by EskiMaq gives the following results :