How to resolve the algorithm Bulls and cows step by step in the Elixir programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Bulls and cows step by step in the Elixir programming language
Table of Contents
Problem Statement
Bulls and Cows is an old game played with pencil and paper that was later implemented using computers.
Create a four digit random number from the digits 1 to 9, without duplication. The program should:
The score is computed as:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Bulls and cows step by step in the Elixir programming language
Source code in the elixir programming language
defmodule Bulls_and_cows do
def play(size \\ 4) do
secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
play(size, secret)
end
defp play(size, secret) do
guess = input(size)
if guess == secret do
IO.puts "You win!"
else
{bulls, cows} = count(guess, secret)
IO.puts " Bulls: #{bulls}; Cows: #{cows}"
play(size, secret)
end
end
defp input(size) do
guess = IO.gets("Enter your #{size}-digit guess: ") |> String.strip
cond do
guess == "" ->
IO.puts "Give up"
exit(:normal)
String.length(guess)==size and String.match?(guess, ~r/^[1-9]+$/) ->
String.codepoints(guess)
true -> input(size)
end
end
defp count(guess, secret) do
Enum.zip(guess, secret) |>
Enum.reduce({0,0}, fn {g,s},{bulls,cows} ->
cond do
g == s -> {bulls + 1, cows}
g in secret -> {bulls, cows + 1}
true -> {bulls, cows}
end
end)
end
end
Bulls_and_cows.play
You may also check:How to resolve the algorithm Multiplicative order step by step in the C programming language
You may also check:How to resolve the algorithm Magic squares of odd order step by step in the Haskell programming language
You may also check:How to resolve the algorithm Unix/ls step by step in the zkl programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the 68000 Assembly programming language
You may also check:How to resolve the algorithm Convert seconds to compound duration step by step in the Wren programming language