user3601148
user3601148

Reputation: 185

Generating possible unordered pairs of combinations from a Hashset

I realise that this question may have been asked many times before, but for this particular application using loops won't really work because I can't index into a set

What I'm looking to do is getting a set of possible unordered pairs from data in a hashset as efficiently as possible.

So if my hashset contained A, B, C, D , E Then the following combinations are possbile: AB, AC, AD, AE, BC, BD, BE, CD, CE, DE

What options do I have available to achieve this efficiently?

Any ideas would be greatly appreciated

Upvotes: 1

Views: 800

Answers (3)

Anderson Marques
Anderson Marques

Reputation: 17

There aren't too may options. You can arrange your objects in an imutable object Class with the two objects like this:

public T Class Arrangement<T>{
      private final T object1;
      private final T object2;

      public Arrangement(T object1, T)

      // get methods... 
}

Set<MyType> mySet = new HashSet<MyType>();

mySet.add(new Arrangement(myObject1, myObject2);

Something like this!

Upvotes: 0

Pham Trung
Pham Trung

Reputation: 11294

You can still index your data, just add an additional HashMap<Your_Class, Integer> map to store the index of a particular data.

 HashSet<Your_Class> set = ...//HashSet that contains data
 int index = 0;
 HashMap<Your_Class,Integer> map = new HashMap<>();
 for(Your_Class item : set){
     map.put(item, index++);
 }
 //Generate all the set with those indexes, and replace them with map.get(index)

So, in the example case, A has index 0, B has index 1,...., So for each pair 01, 02, 03..., just need to convert it back into AB, AC ,...

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

As far as the efficiency goes, there aren't too many options out there: you need to produce a set of N2 items, meaning that the timing would also be at least of the same order.

Since enumerating a set is linear, two nested loops will deal with this as efficiently as any other method would.

The loop on the outside should iterate the collection from the beginning. The loop on the inside should start at the position of the outer loop's iterator, incremented by one position.

Upvotes: 1

Related Questions