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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探