Created
July 18, 2016 05:39
-
-
Save xuzhenglun/7a14016e9e1e83e86042d072ef54edf3 to your computer and use it in GitHub Desktop.
Guess the code
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" | |
"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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
666