Golang 中国

https://my.oschina.net/bowu/blog/789475 这个翻译的

结果老是跟PHP对不上,请各位指教,先谢谢了(我个人认为问题应该出在 cards = append(cards[:k], cards[k+1:]…) //删除指定的元素 这行)

package main

import (
    "fmt"
    "strconv"
)

func main() {
    cards := []string{"01", "02", "07", "04", "06"}
    //cards := []string{"08", "02", "07", "04", "06"}
    fmt.Println(niu(cards))
}

//将字符串数组转换成整数数组
func toNumArray(strarray []string) []int {
    var numArray = []int{}
    for i := 0; i < len(strarray); i++ {
        v, _ := strconv.Atoi(strarray[i])
        numArray = append(numArray, v)
    }
    return numArray
}
func niu(cardarr []string) int {
    cards := toNumArray(cardarr) //转换为整数
    var bakcards = []int{0, 0, 0, 0, 0}
    copy(bakcards, cards)

    //所有有牛的组合
    var nius = [21][3]int{{1, 1, 8}, {1, 2, 7}, {1, 3, 6}, {1, 4, 5}, {2, 3, 5}, {2, 2, 6}, {2, 4, 4}, {3, 3, 4}, {10, 9, 1}, {10, 8, 2}, {10, 7, 3}, {10, 6, 4}, {10, 5, 5}, {9, 8, 3}, {9, 7, 4}, {9, 6, 5}, {8, 7, 5}, {8, 8, 4}, {8, 6, 6}, {7, 7, 6}, {10, 10, 10}}
    flag := false //默认没有牛

    for _, niu := range nius {
        var fnum int = 1
        for k, v := range niu {
            if in_array(cards, v) {
                fnum++
                cards = append(cards[:k], cards[k+1:]...) //删除指定的元素
            }
        }

        if fnum > 2 {
            flag = true
            break
        } else {
            cards = []int{-1, -1, -1, -1, -1}
            copy(cards, bakcards)
        }
    }

    if flag {
        niunum := (cards[0] + cards[1]) % 10
        if niunum == 0 {
            return 10
        } else {
            return niunum
        }
    } else {
        return 0
    }
}

func in_array(array []int, v int) bool {
    for i := 0; i < len(array); i++ {
        if v == array[i] {
            return true
        }
    }
    return false
}

sgbl888 于 2017-09-07 22:18 修改
2 回复
heimeil
#1 heimeil • 2017-09-08 11:55

1 > fnum := 0
2 > cards = append(cards[:k], cards[k+1:]...) 这里的k错了,是niu的下标,永远是0 1 2,需要去取v在cards里的下标,最好在in_array中找到就返回下标,没找到就返回-1。

sevenhe
#2 sevenhe • 2017-09-21 23:06

怎么没找到赞同的按钮。。。

需要 登录 后方可回复, 如果你还没有账号你可以 注册 一个帐号。