groovy/java check list intersections and combine elements

血红的双手。 提交于 2019-12-12 06:09:25

问题


I have a list:

def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]

I need to check intersections and if two lists intersect, combine them.

The result should be as follows:

def b = [[14, 17, 12, 5, 8, 3, 2], [9]]

(i.e 14 is in first sublist, which is also in second sublist, and recursively so on...) How this task can be solved?


回答1:


You can do something like this in Groovy:

def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]

def rslt = a.inject( [ ] ) { c, n ->
  for( cc in c ) {
    if( n.find { it in cc } != null ) {
      cc.addAll( n )
      cc = cc.unique()
      return c
    }
  }
  c << n
}

assert rslt == [[14, 17, 12, 5, 8, 3, 2], [9]]



回答2:


Here is another example using some of Groovy's set "inspired" methods on lists

def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]

def res = a.inject([]){ acc,val ->
    def isect =  acc.find{ val.intersect(it)}?.with{ it.addAll(val - it) }
    !isect ? acc << val : acc
}

assert res.containsAll([[14, 17, 12, 5, 8, 3, 2], [9]])


来源:https://stackoverflow.com/questions/15816396/groovy-java-check-list-intersections-and-combine-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!