1

I'm trying to find a good approach to solve quite simple problem. For example, let us say that there are three sets (there might be more):

Set<Integer> A = [1,2,3,4,5,6]
Set<Integer> B = [2,4,6,8,10]
Set<Integer> C = [1,3,6,9]

Now, how to find answer to this equation: (A or B) and (B or C). Basically and and or are intersection and union. So the answer to this would be just a single set. The answer to above operation would be:

[1,2,3,4,6,8,10]

I have done methods that find union and intersection with two sets, but I'm stuck in the point where there might be more than one operation in the equation. And the operation length depends on the user input. It might be different each time

// intersection
private Set<Integer> intersection(Set setA, Set setB){
            return (Set<Integer>) setA.stream()
                 .filter(setB::contains)
                 .collect(Collectors.toSet());
        }
// union
   private Set<Integer> union(Set setA, Set setB){
    Set<Integer> result = new HashSet<Integer>(setA);
    result.addAll(setB);
    return result;
}

All approaches in Stackoverflow are based on two sets...

AverageJoe9000
  • 348
  • 1
  • 14
  • How about `Set.retainAll()`? – radoh Mar 22 '17 at 13:43
  • What about it? My intersection method is faster than retainAll(). – AverageJoe9000 Mar 22 '17 at 13:45
  • `intersaction(union(A,B),union(B,C));` shall do the job ? – Sanjeev Mar 22 '17 at 13:49
  • 1
    It does, but if you read the question carefully, it says that the equation might be dynamic. So one time it might be `(A or B) and C`, the other time `A or C and B`...It depends on what user asks or types – AverageJoe9000 Mar 22 '17 at 13:54
  • 1
    *My intersection method is faster than retainAll*, I'd be careful with such statements, I'd say it is at most as fast as Set's `retainAll()`. – radoh Mar 22 '17 at 14:31
  • 1
    But honestly the question isn't very clear - is this about **parsing user's input**? I.e. if user enters `(A or B) and C` then program acts accordingly, e.g. `intersection(union(A, B), C)`, etc – radoh Mar 22 '17 at 14:33
  • Yes, basically, that is what I am looking for. – AverageJoe9000 Mar 22 '17 at 14:35
  • 1
    Then you may wanna look at this question for example http://stackoverflow.com/questions/114586/smart-design-of-a-math-parser, but instead of the usual math operators you'll use your Set operators/operations. – radoh Mar 22 '17 at 14:46
  • I will take a look. Cheers! – AverageJoe9000 Mar 22 '17 at 14:55

0 Answers0