dongleman4760 2018-06-16 05:17
浏览 28
已采纳

递归而不是循环[关闭]

I'm new in Go programming, so how to implement recursion instead of a for loop in this code?

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条回答 默认 最新

  • dqblm40280 2018-06-16 16:06
    关注

    I am not sure what you want to be recursive. But as I understand your question as changing a for-loop into a recursion, I made it into a tail recursion in a closure, in a functional programing style.

    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)
    }
    

    If you want the matter simpler, you can remove the closure part and move the line Scan(&a[n-i]) behind the line setRecursive(n), Like below:

    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])
    }
    

    Playground: https://play.golang.org/p/0io190tyviE

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能