word = "apple"
tempWord =
String.codepoints(word)
|> Enum.with_index()
|> Enum.map(fn {char, index} ->
cond do
char == String.at(guess, index) -> {char, index, :correct}
true -> {char, index, :null}
end
end)
# [{"a", 0, :null}, {"p", 1, :null}, {"p", 2, :null}, {"l", 3, :correct}, {"e", 4, :null}]
guess = "hello"
tempGuess =
String.codepoints(guess)
|> Enum.with_index()
|> Enum.map(fn {char, index} ->
cond do
char == String.at(word, index) -> {char, index, :correct}
not String.contains?(word, char) -> {char, index, :wrong}
String.contains?(word, char) -> {char, index, :maybe}
end
end)
# [{"h", 0, :wrong}, {"e", 1, :maybe}, {"l", 2, :maybe}, {"l", 3, :correct}, {"o", 4, :wrong}]
In the above code, what would be the Elixir way to achieve the following:
- Take each element of
guessTemp
- if the state is
maybe
, then check thewordTemp
list; - find the first occurrence of a corresponding character, if the state is
:null
, then - in
wordTemp
, change the state from:null
to:done
- back to item 2; if there is no such occurrence in
wordTemp
, change the status of the entry inguessTemp
as:incorrect
Thus, for the above example, the final list should be in the form of:
[{"h", 0, :wrong}, {"e", 1, :maybe}, {"l", 2, :maybe}, {"l", 3, :correct}, {"o", 4, :wrong}]