douhuan1937 2017-07-23 17:30 采纳率: 0%
浏览 19
已采纳

在Golang中生成powerset的代码给出了错误的结果

Next code in Golang to generate powerset produces wrong result on input {"A", "B", "C", "D", "E"}. I see [A B C E E] as the last generated set.

package main

import (
    "fmt"
)

func main() {
    for _, s := range PowerSet([]string{"A", "B", "C", "D", "E"}) {
        fmt.Println(s)  
    }   
}

func PowerSet(set []string) [][]string {
    var powerSet [][]string
    powerSet = append(powerSet, make([]string, 0))
    for _, element := range set {
        var moreSets [][]string
        for _, existingSet := range powerSet {
            newSet := append(existingSet, element)
            moreSets = append(moreSets, newSet)
        }
        powerSet = append(powerSet, moreSets...)
    }
    return powerSet
}

How to fix it? How to write it idiomatically in Go?

  • 写回答

3条回答 默认 最新

  • duanhuilao0787 2017-07-23 18:25
    关注

    The problem with your program is not the algorithm itself but this line:

    newSet := append(existingSet, element)
    

    You should not append and assign to a different variable.

    As the documentation states (emphasis mine), "The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated.".

    So, there might be cases where newSet := append(existingSet, element) will actually modify existingSet itself, which would break your logic.

    If you change that to instead create a new array and append to that one, it works as you expect it.

    newSet := make([]string, 0)
    newSet = append(newSet, existingSet...) 
    newSet = append(newSet, element)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器