douliaodun9153 2018-09-27 13:40
浏览 259
已采纳

尝试在Go中实现Java Guava sets.difference

Java Guava Sets.difference behavior:

Known = ["v1","v2"]; Incoming = ["v2","v3","v4"]

incoming = ["v2","v3","v4"]; knownUpdated = ["v2"]

Sets.difference(Known, Incoming) = v1 (To be removed)

Sets.difference(incoming, knownUpdated) = v3,v4 (To be added)

What I have tried in Go is giving the below difference:

Output := [v1 v3 v4] (known, Incoming) 

func Difference(slice1 []string, slice2 []string) []string {
    var diff []string

    for i := 0; i < 2; i++ {
        for _, s1 := range slice1 {
            found := false
            for _, s2 := range slice2 {
                if s1 == s2 {
                    found = true
                    break
                }
            }

            if !found {
                diff = append(diff, s1)
            }
        }
        if i == 0 {
            slice1, slice2 = slice2, slice1
        }
    }

    return diff
}

Its giving symmetric difference but I need the behavior of Guava sets.difference. I know something is wrong with my func. From the guava documentation of public static Sets.SetView difference(Set set1, Set set2):The returned set contains all elements that are contained by set1 and not contained by set2

  • 写回答

1条回答 默认 最新

  • dtwd74916 2018-09-27 14:06
    关注

    The most straight-forward and easy to understand solution is that of using maps - if you use only the keys, discarding the values, they share similar properties to many other set implementations (O(1) lookup*, unique keys, unordered). At which point, it's actually quite trivial:

    func Difference(slice1 []string, slice2 []string) []string {
        // Create proper "set" (Maps have unordered pairs and the keys are unique;
        // lookup to check whether value is present is O(1), similar to other
        // implementations)
        m := make(map[string]struct{}, len(slice1))
        for _, el := range slice1 {
            m[el] = struct{}{}
        }
    
        // Remove values from slice1 present in slice2
        for _, el := range slice2 {
            delete(m, el)
        }
    
        // Note that res will be non-deterministic: the order of iteration over maps
        // is made random on purpose by Go itself
        res := make([]string, 0, len(m))
        for k := range m {
            res = append(res, k)
        }
        return res
    }
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛