go語言版的猜數字遊戲

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

猜數字(Bulls and Cows)是一個經典的小遊戲.
程式先產生4位各不相同的隨機數,然後使用者輸入0-9四位各不相同的數字,程式將輸入的數字與隨機數進行對比,位置和數字對應相同者提示為xA,數字相同而位置不同者提示為xB,共15次機會.如隨機數為1543,輸入5134將提示0A4B,輸入1534將提示2A2B,輸入1543將提示4A0B(此時使用者獲勝).
這個遊戲邏輯簡單但代碼實現富有挑戰性,非常適合編程練手使用.最近學習go語言中,下面是go語言版的Bulls and Cows:

package mainimport (    "fmt"    "time"    "math/rand"    "os")func gen_num(length int)[]int32{    a:=[]int32{1,2,3,4,5,6,7,8,9,0}    b:=make([]int32,length,length)    if length>10 || length<0{        fmt.Println("invalid length:",length)        os.Exit(-1)    }    r:=rand.New(rand.NewSource(time.Now().UnixNano()))    for i:=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]    }    return b}func check_num(a,b []int32)bool{    var aa,bb int    if len(a)!=len(b){        return false    }    dict:=make(map[int32]int)    for i:=0;i<len(a);i++{        dict[a[i]]=0    }    for i:=0;i<len(a);i++{        if _,ok:=dict[b[i]];ok{            bb++        }    }    for i:=0;i<len(a);i++{        if a[i]==b[i]{            aa++        }    }    bb=bb-aa    fmt.Printf("%dA%dB\n",aa,bb)    if aa==len(a){        fmt.Println("OK!")        return true    }else{        return false    }}func main(){    var ipu int32    var i int    status:=false    length:=4    src:=gen_num(length)    tmp:=make([]int32,length,length)    for j:=0;j<15 && !status;j++{        fmt.Printf("Please input %d numbers\n",length)        fmt.Scanf("%d",&ipu)        for i=0;ipu>0;i++{            tmp[i]=ipu%10            ipu=ipu/10        }        if i<length{            tmp[i]=0        }        dest:=make([]int32,length,length)        for i:=0;i<len(tmp);i++{            dest[length-1-i]=tmp[i]        }        status=check_num(src,dest)    }}

運行:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.