【问题标题】:How to make a go program recursive如何使 Go 程序递归
【发布时间】:2016-05-01 06:51:00
【问题描述】:

我怎样才能使这个 go 程序递归。我正在通过编写游戏编号分析器来学习 golang。我一直在思考如何做到这一点,但无法提出可行的解决方案。这是Google Playground. 中的链接 任何帮助将不胜感激。

/*
File record.go
Author: Dan Huckson
Date: 20160120
Purpose: Number analyzer
*/
package main

import (
    "fmt"
)

type Stats struct {
    category map[string]Events
}

type Events struct {
    event map[string]*Event
}

type Event struct {
    value int64
}

func main() {
    winners := [][]int{
        {1, 2, 3, 4, 5, 6},
        {2, 4, 6, 28, 26, 39},
        {1, 4, 9, 10, 26, 39},
        {1, 9, 19, 29, 26, 49},
        {4, 5, 6, 28, 26, 49}}

    keys := []string{"digits1", "digits2", "digits3", "digits4", "digits5", "digits6"}

    stats := new(Stats)
    stats.category = make(map[string]Events)

    for _, key := range keys {
        events, ok := stats.category[key]
        if !ok {
            events = *new(Events)
        }
        events.event = make(map[string]*Event)
        stats.category[key] = events

    }
    fmt.Println()

    for _, winner := range winners {
        fmt.Println(winner)
        stats.digits1("digits1", winner)
        stats.digits2("digits2", winner)
        stats.digits3("digits3", winner)
        stats.digits4("digits4", winner)
        stats.digits5("digits5", winner)
        stats.digits6("digits6", winner)
    }
}

func (stats *Stats) record(key string, balls string) {

    event, ok := stats.category[key].event[balls]
    if !ok {
        event = new(Event)
        stats.category[key].event[balls] = event
    }
    stats.category[key].event[balls].value += 1

    word := ""
    if len(balls) > 1 {
        word = "Balls"
    } else {
        word = "Ball"
    }

    fmt.Printf("%s:%s\tCount:%d\n", word, balls_to_csv(balls), stats.category[key].event[balls].value)
}

func (stats *Stats) digits1(key string, winner []int) {
    for i := 0; i < len(winner); i++ {
        stats.record(key, string(winner[i]))
    }
}

func (stats *Stats) digits2(key string, winner []int) {
    for i := 0; i < len(winner)-1; i++ {
        for j := i + 1; j < len(winner); j++ {
            stats.record(key, string(winner[i])+string(winner[j]))
        }
    }
}

func (stats *Stats) digits3(key string, winner []int) {
    for i := 0; i < len(winner)-2; i++ {
        for j := i + 1; j < len(winner)-1; j++ {
            for k := j + 1; k < len(winner); k++ {
                stats.record(key, string(winner[i])+string(winner[j])+string(winner[k]))
            }
        }
    }
}

func (stats *Stats) digits4(key string, winner []int) {
    for i := 0; i < len(winner)-3; i++ {
        for j := i + 1; j < len(winner)-2; j++ {
            for k := j + 1; k < len(winner)-1; k++ {
                for l := k + 1; l < len(winner); l++ {
                    stats.record(key, string(winner[i])+string(winner[j])+string(winner[k])+string(winner[l]))
                }
            }
        }
    }
}

func (stats *Stats) digits5(key string, winner []int) {
    for i := 0; i < len(winner)-4; i++ {
        for j := i + 1; j < len(winner)-3; j++ {
            for k := j + 1; k < len(winner)-2; k++ {
                for l := k + 1; l < len(winner)-1; l++ {
                    for m := l + 1; m < len(winner); m++ {
                        stats.record(key, string(winner[i])+string(winner[j])+string(winner[k])+string(winner[l])+string(winner[m]))
                    }
                }
            }
        }
    }
}

func (stats *Stats) digits6(key string, winner []int) {
    for i := 0; i < len(winner)-5; i++ {
        for j := i + 1; j < len(winner)-4; j++ {
            for k := j + 1; k < len(winner)-3; k++ {
                for l := k + 1; l < len(winner)-2; l++ {
                    for m := l + 1; m < len(winner)-1; m++ {
                        for n := m + 1; n < len(winner); n++ {
                            stats.record(key, string(winner[i])+string(winner[j])+string(winner[k])+string(winner[l])+string(winner[m])+string(winner[n]))
                        }
                    }
                }
            }
        }
    }
}

func balls_to_csv(key string) string {
    s := ""
    length := len(key)
    for i := 0; i < length; i++ {
        s += fmt.Sprintf("%d,", key[i])
    }
    return s[:len(s)-1]
}

【问题讨论】:

  • 您必须提供更多信息。例如,您想使用递归来实现什么?为什么你的代码不起作用?
  • 如果您查看函数,“digits1() 到 digits6()”,它们在记录函数中具有或多或少的嵌套和不同的字符串长度相似。我敢肯定,比我有更多编码经验的人以前见过这种模式,并且可以将其转换为递归函数。我目前有这些方法是静态编写的,这不是最好的解决方案。我以前写过递归方法,但我似乎对此想不出任何办法。拥有一个动态的、可能是递归的数字#() 函数将使游戏更具动态可修改性。

标签: arrays recursion go


【解决方案1】:

据我所知,您想递归地找到所有中奖号码的组合。例如,

package main

import "fmt"

func combinations(n []int, c []int, ccc [][][]int) [][][]int {
    if len(n) == 0 {
        return ccc
    }
    if len(ccc) == 0 {
        ccc = make([][][]int, len(n))
    }
    for i := range n {
        cc := make([]int, len(c)+1)
        copy(cc, c)
        cc[len(cc)-1] = n[i]
        ccc[len(cc)-1] = append(ccc[len(cc)-1], cc)
        ccc = combinations(n[i+1:], cc, ccc)
    }
    return ccc
}

func main() {
    n := []int{1, 2, 3, 4}
    fmt.Println("winning numbers", n)
    fmt.Println()
    nw := 0
    w := combinations(n, nil, nil)
    fmt.Println("winning tickets:")
    d := " digit : "
    for i := range w {
        fmt.Print(i+1, d)
        d = " digits: "
        for j := range w[i] {
            nw++
            fmt.Print(w[i][j], " ")
        }
        fmt.Println()
    }
    fmt.Println()
    fmt.Println(nw, "winners")
}

输出:

winning numbers [1 2 3 4]

winning tickets:
1 digit : [1] [2] [3] [4] 
2 digits: [1 2] [1 3] [1 4] [2 3] [2 4] [3 4] 
3 digits: [1 2 3] [1 2 4] [1 3 4] [2 3 4] 
4 digits: [1 2 3 4] 

15 winners

化简,可以看到递归。

func combinations(n []int) {
    if len(n) == 0 {
        return 
    }
    for i := range n {
        combinations(n[i+1:])
    }
    return 
}

递归在len(n) == 0 时终止。在for循环中,i增加到len(n)-1combinations(n[i+1:])变成combinations(n[len(n):])len(n[len(n):]) == 0,这将终止递归。

【讨论】:

  • 非常感谢,我以前写过递归函数,但没有那么复杂。看着(play.golang.org/p/-kNjWKOzdZ" 我写的代码),它只是为了递归而哭泣。我正在查看(play.golang.org/p/suoVTWpQvv"您的解决方案)并且不知道发生了什么。我会花时间研究它,直到我这样做为止。再次感谢!
【解决方案2】:

递归不是特定于语言的概念。如果你知道什么是递归,如果你知道如何在 Go 中编写函数,那么你可以在 Go 中编写递归函数。

这是 Go 中的一个虚拟递归函数。

func f(n int) int {
    if n < 0 {
        return 0 // or something else
    }
    if n == 0 {
        return 1
    }
    return n * f(n - 1)
}

这是 Go 中的递归函数,因为,

  1. 它有一个终止(基础)条件(n
  2. f(n) 取决于所有 x
  3. 它是用 Go 编写的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-07
    • 2022-12-20
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2013-01-18
    相关资源
    最近更新 更多