Groovy language: how to get the difference between two pairs lists

I am trying to get the difference in 1 list of pairs from another in Groovy language. Pairs are just (x, y) coordinates, and they are unique. Below is a small example for simplicity. Please note that lists can have dozens of pairs.

def l1 = [[x:1, y:1]] def l2 = [[x:0, y:0]] println l1 - l2 

will receive [], that is, an empty list, but should be as follows: [[x: 1, y: 1]]

Update:

  for(n in l2) { l1 = l1 - n } 

It works, but it's black magic and not optimized.

+6
source share
1 answer

As stated in the comments, the pairs in l1 unique (or rather: this is normal to have unique results), then you can use l1 / l2 as sets:

 l1 = [[x:1, y:1]] l2 = [[x:0, y:0]] println l1.toSet()-l2.toSet() //; [[x:1, y:1]] 

Initially, the problem is in the [x:0,y:0] vs [x:1,y:1] . The reason is public static <T> Collection<T> minus(Collection<T> self, Collection<?> removeMe) . N * n branches are NumberAwareComperator and NumberAwareComperator considers both cards to be equal:

 def cmp = new org.codehaus.groovy.runtime.NumberAwareComparator() println cmp.compare(l1[0], l2[0]) //; 0 (equal!) 

It just comes down to:

 assert [x:1, y:1].hashCode() == [x:0, y:0].hashCode() // 120^1 + 121^1 == 120^0 + 121^0 

Change Alternative (if you can get rid of the card)

Since this is not well suited for the database, you might be better off using a save and sound class comparable to your data. eg:.

 @groovy.transform.Immutable class Pair { long x,y } def p00 = new Pair(0,0) def p11 = new Pair(1,1) def p11o = new Pair(1,1) assert [p00]-[p11] == [p00] assert [p11]-[p00] == [p11] assert [p00].intersect([p11]) == [] assert [p11].intersect([p00]) == [] assert [p11].intersect([p11o]) == [p11] assert [p11].intersect([p11o]) == [p11o] 

Even map rotation in Expando works better.

+6
source

Source: https://habr.com/ru/post/978903/


All Articles