duannaoye0732 2017-06-24 01:56 采纳率: 100%
浏览 39

递归旅行推销员喜欢去计算

I have a function that is somewhat similar to the traveling salesman problem that I am trying to make recursive. I think it is working but I am having some trouble getting the appending to work correctly on large datasets. Here is what I have...main should be written to be recursive so I can call a variable number of recursions...https://play.golang.org/p/Lz8arHybFr

package main

type Foo struct {
    StartPoint string
    EndPoint string 
    distance int
}

func (f *Foo) Connects(endFoo *Foo) bool {
    return f.EndPoint == endFoo.StartPoint
}

func (f *Foo) Completes(endFoo *Foo) bool {
    return f.StartPoint == endFoo.EndPoint
}

var fl = []*Foo{
    // many foo in here
}

func main() {

    completeList := [][]*Foo{}

    for _, first := range fl {
        for _, second := range fl {
            if second.Connects(first) {
                if second.Completes(first) {
                    l := []*Foo{
                        first, second,
                    }
                    completeList = append(completeList, l)
                }

                //if the connection is made, but not complete, keep going
                for _, third := range fl {
                    if third.Connects(second) {
                        if first.Completes(third) {
                            l := []*Foo{
                                first, second, third,
                            }
                            completeList = append(completeList, l)
                        }
                    }
                }
            }
        }
    }

}
  • 写回答

1条回答 默认 最新

  • doupoji3856 2017-06-26 06:44
    关注

    I came up with 2 recursions, please, check it on your data: (I suppose you're going to make this parallel, so this will be easier with 2 recursions, just as a go rec2(...))

    func main() {
        rec(0,0)
    }
    
    func rec(a, b int) {
        if a >= len(fl) || b >= len(fl) || a == b {
            return
        }
        aa, bb := fl[a], fl[b]
        if !aa.Connects(bb) {
            rec(a, b+1)
            return
        }
        l := []*Foo{
            aa, bb,
        }
        completeList = append(completeList, l)
    
        rec2(0, a, b)
    }
    
    func rec2(c, a, b int) {
        if c >= len(fl) || a == c || b == c {
            return
        }
        cc, aa, bb := fl[c], fl[a], fl[b]
        if cc.Connects(bb) && aa.Completes(cc) {
             l := []*Foo{
                  aa, bb, cc,
             }
             completeList = append(completeList, l)
        }
        rec2(c+1, a, b)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败