douxingsuo8809 2016-02-22 07:27
浏览 30
已采纳

编写深度为d的嵌套迭代器

How to realize a nested iterator that takes a depth argument. A simple iterator would be when depth = 1. it is a simple iterator which runs like a simple for loop.

func Iter () chan int {
    ch := make(chan int);
    go func () {
        for i := 1; i < 60; i++ {
            ch <- i
        }
        close(ch)
    } ();
    return ch
}

Output is 1,2,3...59

For depth = 2 Output would be "1,1" "1,2" ... "1,59" "2,1" ... "59,59"

For depth = 3 Output would be "1,1,1" ... "59,59,59"

I want to avoid a nested for loop. What is the solution here ?

  • 写回答

2条回答 默认 最新

  • duan1930 2016-02-22 08:10
    关注

    I don't know if it is possible to avoid nested loops, but one solution is to use a pipeline of channels. For example:

    const ITER_N = 60
    
    // ----------------
    
    func _goFunc1(out chan string) {
        for i := 1; i < ITER_N; i++ {
            out <- fmt.Sprintf("%d", i)
        }
        close(out)
    }
    
    func _goFuncN(in chan string, out chan string) {
        for j := range in {
            for i := 1; i < ITER_N; i++ {
                out <- fmt.Sprintf("%s,%d", j, i)
            }
        }
        close(out)
    }
    
    // ----------------
    
    // create the pipeline
    func IterDepth(d int) chan string {
        c1 := make(chan string)
        go _goFunc1(c1)
    
        var c2 chan string
        for ; d > 1; d-- {
            c2 = make(chan string)
            go _goFuncN(c1, c2)
            c1 = c2
    
        }
        return c1
    }
    

    You can test it with:

    func main() {
        c := IterDepth(2)
    
        for i := range c {
            fmt.Println(i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3