douzhang5199 2018-12-14 09:18
浏览 78
已采纳

如何将一个切片与其他切片进行比较以查看内容是否匹配

Using Go 1.11 I have 5 group of three numbers each in their own slice. I want to be able to compare that to a core data set.

Example data

My Groups: [[1 2 3] [4 9 2] [7 9 3] [4 7 5] [4 3 2]]

My Core Data: [5 9 7 3 2]

So I want to be able to match my core data up with any of the groups. As the example data shows, the core data does have 9, 7 and 3 so it should match the 3rd group.

But each time I try to loop, I am not getting the logic right.

Any help most welcome.

UPDATE

So this is the code I am currently working with

groupData := [][]int{{1,2,3}, {7,8,9}, {9,7,3}}
coreData := []int{5,9,7,3,2}

for _, data := range groupData {
   fmt.Println( data )
   fmt.Println( groupData )

   fmt.Println( reflect.DeepEqual(data, coreData) )
}

This returns false all the time. Even on the last set of data 9,7,3 which you can see is contained within the codeData var.

But even if I had a coreData like []int{3,2,7,1,9} that should still result in true, as it still has 3,7,9 and I want to it match that last group.

Hope that explains what I am looking to do more. Thanks.

  • 写回答

1条回答 默认 最新

  • drvc63490 2018-12-14 09:35
    关注

    This is an update of my previous answer because you need a partial match.

    As you want to have a partial match you cannot use deep equals.

    But you can do something like this.

    func main() {
        groupData := [][]int{{1,2,3}, {7,8,9}, {9,7,3}}
        coreData := []int{5,9,7,3,2}
    
        // Loop over each group to check a partial match against core
        for _, data := range groupData {
           fmt.Println( check(data, coreData ))
    
        }
    }
    
    func check(group, core[]int) bool {
        // Loop over each group element to check if its available in core
        for _, s := range group{
            if contains(core, s) == false {
                return false
            }   
        }
        return true
    }
    
    // Returns true if core contains the element
    func contains(core []int, element int) bool {
        for _, a := range core {
            if a == element {
                return true
            }
        }
        return false
    }
    

    This result in :

    false

    false

    true

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题