Last active
September 9, 2019 20:34
-
-
Save cmbrown1598/6dca471a34fa64319d3f35f04bfa29ec to your computer and use it in GitHub Desktop.
This file contains 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
type Response = | Bull | Cow | Empty | |
let bullAndCow (attempt : int[]) (answer : int[]) = | |
let bullCowOrNothing (idx:int) (chr:int) = | |
if (answer.[idx] = chr) then Bull | |
else if (Array.contains chr answer) then Cow | |
else Empty | |
Array.mapi bullCowOrNothing attempt |> Array.filter (fun n -> n <> Empty) | |
let rec getGuess() = | |
printf "Enter your guess. " | |
let guess = System.Console.ReadLine() | |
match guess.ToCharArray() with | |
| s when Array.forall System.Char.IsDigit s && Array.length s = 4 -> | |
Array.map (fun c -> System.Int32.Parse(c.ToString())) s | |
| _ -> getGuess() | |
let pluralize (item, count) = | |
if count > 1 then sprintf "%d %As" count item | |
else sprintf "1 %A" item | |
let rec generateAnAnswer set = | |
let r = System.Random(); | |
let res = Set.add (r.Next(0, 9)) set | |
if Set.count res = 4 then res | |
else generateAnAnswer res | |
let playPersonGuessesComputer() = | |
let computersAnswer = generateAnAnswer Set.empty |> Set.toArray | |
let rec play guesses = | |
let guess = getGuess() | |
let guessCount = guesses + 1 | |
let result = bullAndCow guess computersAnswer | |
if Array.forall (fun r -> r = Bull) result && Array.length result = 4 then | |
printfn "You win, in %d guesses" guessCount | |
guessCount | |
else | |
let counts = Array.sort result |> Array.countBy id | |
if Array.length counts > 1 then printfn "Good try! You got %s and %s." (pluralize counts.[0]) (pluralize counts.[1]) | |
else if Array.length counts = 1 then printfn "Good try! You got %s." (pluralize counts.[0]) | |
else printfn "Good try! None of these are in the answer!" | |
play guessCount | |
play 0 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment