This is a creation in Article, where the information may have evolved or changed.
Guessing numbers (Bulls and cows) is a classic little game.
The program first produces 4-bit different random numbers, and then the user input 0-9 four bits of different numbers, the program will enter the number and the random number, the position and the number corresponding to the same person prompts for XA, the same number and the location of the different people prompted for XB, a total of 15 opportunities. If the random number is 1543, enter 5134 will prompt 0a4b, enter 1534 will prompt 2a2b, enter 1543 will prompt 4a0b (at this time the user wins).
The logic of this game is simple but the code is very challenging, and it is very suitable for programming practiced hand. Recently learning the Go language, the following is the go language version of bulls and cows:
Package Mainimport ("FMT" "Time" "Math/rand" "OS") Func Gen_num (lengthint) []int32{a: =[]int32{1,2,3,4,5,6,7,8,9,0} b:=make ([]int32,length,length)if length>Ten||length<0{FMT. Println ("Invalid length:",length) OS. Exit (-1)} r:=rand. New (Rand. Newsource ( Time. Now (). Unixnano ())) fori:=0;i<length; i++{Tmp:=r.intn (Len(a)-i) b[i]=a[TMP]a[TMP],a[Len(a)-1-i]=a[Len(a)-1-I.],a[TMP]}returnB}func Check_num (a, b []int32) bool{var aa,bb intif Len(a)!=Len(b) {return false} dict:=make (Map[int32]int) fori:=0;i<Len(a); i++{dict[a[I]] =0} fori:=0;i<Len(a); i++{if_,ok:=dict[b[i]];ok{bb++}} fori:=0;i<Len(a); i++{if a[I]==b[i]{aa++}} bb=bb-aa fmt. Printf ("%da%db\n", AA,BB)ifaa==Len(a) {FMT. Println ("ok!")return true}Else{return false}}func Main () {var ipu int32 var i int status:=false length:=4Src:=gen_num (length) Tmp:=make ([]int32,length,length) forj:=0;j< the&&!status;j++{FMT. Printf ("Please input%d numbers\n",length) FMT. SCANF ("%d", &ipu) forI=0;ipu>0; i++{tmp[i]=ipu%Tenipu=ipu/Ten}ifi<length{tmp[i]=0} dest:=make ([]int32,length,length) fori:=0;i<Len(TMP); i++{dest[length-1-i]=tmp[i]} status=check_num (Src,dest)}}
Run: