Reputation: 2419
Assuming I have a set<Integer>
(few thousands).
I want to perform cartesian product but without any duplicates.
A duplicate entry is considered to have the inverse element in the set (i.e. <1,3>
and <3,1>
are considered duplicates).
How can I do it efficiently?
First I use Sets.cartesianProduct(set, set)
which results ~22M elements, but it also contained duplications. iterating that list again to check result.contains(..)
is not efficient at all.
Upvotes: 0
Views: 326
Reputation: 2419
Funny, I've been messing around with this for few hours, and the moment I write a question in Stackoverflow, I suddenly realize the answer myself ;)
Edited following @DmitryGorkovets improvement
for (int i = 0; i < list.size(); i++) {
for (int j = i+1; j < list.size(); j++) {
result.add(new Pair<>(list.get(i), list.get(j)));
}
}
Upvotes: 1