Last active
May 24, 2022 13:50
-
-
Save kalisjoshua/c4ca439d903306e777b5b9ac6eee5b84 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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"os" | |
"strconv" | |
"time" | |
) | |
// type Gamer interface { | |
// Check() (bool, string) | |
// Play() | |
// } | |
type Game struct { | |
Count int | |
Limit int | |
Secret int | |
} | |
func (game *Game) Check (guess int) (bool, string) { | |
game.Count += 1 | |
if guess == game.Secret { | |
return true, "" | |
} else if guess < game.Secret { | |
return false, "low" | |
} else { | |
return false, "high" | |
} | |
} | |
func (game *Game) Play (fn func (int, int, string) int) { | |
var guess int | |
var hint string | |
var success bool | |
for { | |
guess = fn(game.Limit, guess, hint) | |
success, hint = game.Check(guess) | |
if success || game.Count > game.Limit { | |
break | |
} else { | |
fmt.Println(fmt.Sprintf("Your guess (%d) is too %s.", guess, hint)) | |
} | |
} | |
if game.Count > game.Limit { | |
fmt.Println(fmt.Sprintf("Sorry! The secret number was %d.", game.Secret)) | |
} else { | |
fmt.Println(fmt.Sprintf("Congratulations! Correctly guessed the secret number (%d) in %d guesses.", guess, game.Count)) | |
} | |
} | |
type Solver struct { | |
Range []int | |
} | |
func (solver Solver) Rand (limit int, guess int, hint string) int { | |
return 1 + rand.Intn(limit) | |
} | |
func (solver *Solver) Smart (limit int, guess int, hint string) int { | |
if guess == 0 || hint == "" { | |
solver.Range[0] = 1 | |
solver.Range[1] = limit | |
} else { | |
if hint == "high" { | |
solver.Range[1] = guess | |
} else { | |
solver.Range[0] = guess | |
} | |
} | |
return 1 + solver.Range[0] + rand.Intn(solver.Range[1] - solver.Range[0]) | |
} | |
// cmd: go run Game.go 100 | |
func main () { | |
rand.Seed(time.Now().UnixNano()) | |
var limit, _ = strconv.Atoi(os.Args[1]) | |
var secret int = (1 + rand.Intn(limit)) | |
fmt.Println(fmt.Sprintf("The secret is %d.", secret)) | |
var solver = Solver{[]int {1, limit}} | |
var game = Game{0, limit, secret} | |
// game.Play(solver.Rand) | |
game.Play(solver.Smart) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment