递归而不是循环

时间:2018-06-16 05:17:39

标签: arrays loops go recursion

我是Go编程的新手,那么如何在此代码中实现递归而不是for循环?

package main

import (
    "fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    set(n)
}

func set(n int) {
    a := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    fmt.Println(a)
}

2 个答案:

答案 0 :(得分:1)

我不确定你想要什么递归。但是当我理解你的问题是将for循环更改为递归时,我在一个函数编程风格的闭包中将它变成了一个尾递归。

func set(n int) {
    a := make([]int, n)
    var setRecursive func(int) // declare a function variable, which take an int as param.
    setRecursive = func(i int) { // set the function in closure, so a and n is available to it.
        if i == 0 { // end point of the recursion, return.
            return
        }
        Scan(&a[n-i]) // Use fmt.Scan out of playground
        setRecursive(i - 1) // tail recursion.
    }
    setRecursive(n) // call the function, start the recursion.
    fmt.Println(a)
}

如果您希望问题更简单,可以移除封闭部分并将行Scan(&a[n-i])移到行setRecursive(n)后面,如下所示:

func SetRecursive(a []int, n int) {
    if n==0 {
        return
    }

    SetRecursive(a,n-1) // recurse first, so we can scan in the right order.
    Scan(&a[n-1])
}

游乐场:https://play.golang.org/p/0io190tyviE

答案 1 :(得分:0)

我的语法可能有些偏差,所以我评论了每一行的作用。从本质上讲,每次都会获得一个数组项,并在其前面附加一个较小的数组,通过获取一个值并在其前面附加一个较小的数组,直到该值为1,你只是得到了一个价值。

func set(n int) []int {    // declare a function that takes an int as a parameter
                           // and returns an int array
    var recRet = []int{}       // need a temporary array to store return value
    a := make([]int, 1)        // make an array of one to get the value this iteration
    if n < 1 {                   //should never be here but prevents looping
       return nil              // escape
    }
    if n > 1 {                  // if we're not in the base case
        recRet = set(n-1)      // recurse on a list one smaller and store it
    }

    fmt.Scan(&a[1])            // get the value for this iteration
    fmt.Println(a)             // print it
    return append(a, recRet...)// send this value plus the values gotten from recursion
                               // back up
}