package main import "fmt" import _ "os" import "math/rand" const cifre = 4 type Try struct { attempt string gg, gs int } func min(a, b int) int { if a < b { return a } else { return b } } /* Dato un tentativo e un segreto da indovinare, dice quante cifre sono giuste al posto giusto e quante sono giuste al posto sbagliato */ func compare(secret, attempt string) (gg int, gs int) { var contaAttempt, contaSecret map[byte]int contaAttempt = make(map[byte]int) // es. contaAttempt['3'] è il numero di 3 in attempt che non sono giusti al posto giusto contaSecret = make(map[byte]int) // es. contaSecret['3'] è il numero di 3 in secret che non sono giusti al posto giusto for i:=0; i < cifre; i++ { if secret[i] == attempt[i] { gg++ } else { contaAttempt[attempt[i]]++ contaSecret[secret[i]]++ } } for k,_ := range contaSecret { gs += min(contaSecret[k], contaAttempt[k]) } return } /* Dato un possibile valore segreto s, guarda se quel valore segreto darebbe luogo alle risposte ottenute */ func isCompatible(s string, tries []Try) bool { for _, try := range tries { gg, gs := compare(s, try.attempt) if gg != try.gg || gs != try.gs { return false } } return true } func generateAll(length int) []string { var result []string if length == 0 { return []string{""} } for _, x := range generateAll(length - 1) { for i := '0'; i <= '9'; i++ { result = append(result, string(i) + x) } } return result } func generateCompatible(tries []Try) []string { allPossible := generateAll(cifre) actuallyPossible := []string{} for _, x := range allPossible { if isCompatible(x, tries) { actuallyPossible = append(actuallyPossible, x) } } return actuallyPossible } func main() { var tries []Try var gg, gs int for { compatible := generateCompatible(tries) nuovoTentativo := compatible[rand.Intn(len(compatible))] fmt.Println(nuovoTentativo) fmt.Scan(&gg, &gs) if gg == cifre { fmt.Printf("Ho vinto in %d tentativi!\n", len(tries)) break } tries = append(tries, Try{nuovoTentativo, gg, gs}) } }