Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xuzhenglun/7a14016e9e1e83e86042d072ef54edf3 to your computer and use it in GitHub Desktop.
Save xuzhenglun/7a14016e9e1e83e86042d072ef54edf3 to your computer and use it in GitHub Desktop.
Guess the code
package main
import (
"fmt"
"math/rand"
"time"
)
func GeneateCode(n int) []int {
code := make([]int, n)
for i := 0; i < n; i++ {
r := rand.Intn(10)-1
for isIncluded(r, code) {
time.Sleep(1)
r = rand.Intn(9)
}
code[i] = r
time.Sleep(1)
}
return code
}
func isIncluded(n int, array []int) bool {
for _, v := range array {
if n == v {
return true
}
}
return false
}
type InputType struct {
HowMuch map[int]int
Code []int
}
func PudgeInput(n int) *InputType {
var len int
var cp int = n
for cp != 0 {
if cp != 0 {
len++
cp = cp / 10
}
}
code := make([]int, len)
for i := len - 1; i >= 0; i-- {
code[i] = n % 10
n = n / 10
}
howMuch := make(map[int]int)
for _, v := range code {
if _, ok := howMuch[v]; ok {
howMuch[v] = howMuch[v] + 1
} else {
howMuch[v] = 1
}
}
return &InputType{
HowMuch: howMuch,
Code: code,
}
}
func isValid(input []int, n int) bool {
if len(input) != n {
return false
}
return true
}
func main() {
rand.Seed(time.Now().Unix())
n := 4
code := GeneateCode(n)
fmt.Printf("please enter %v number to begin the game\n", n)
//fmt.Println(code)
A, B := 0, 0
chance := 0
for A != len(code) {
var input int
fmt.Printf(">>>")
fmt.Scanln(&input)
if input == 110 {
fmt.Println(code)
}
pudgedInput := PudgeInput(input)
for !isValid(pudgedInput.Code, n) {
fmt.Println("Invalid input! try again")
fmt.Printf(">>>")
fmt.Scanln(&input)
pudgedInput = PudgeInput(input)
}
chance++
A, B = 0, 0
for i, v := range code {
B = B + pudgedInput.HowMuch[v]
if pudgedInput.Code[i] == v {
B--
A++
}
}
fmt.Printf("[A%d] [B%d], you have tried %v times\n", A, B, chance)
}
}
@metayd
Copy link

metayd commented Jul 21, 2016

666

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment