Two Laptop Bag
The moose likes Beginning Java and the fly likes Iterating the hash map to form combinations Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Iterating the hash map to form combinations" Watch "Iterating the hash map to form combinations" New topic
Author

Iterating the hash map to form combinations

Shruthi Babu
Ranch Hand

Joined: May 04, 2007
Posts: 54
I need to iterate a hashmap and form all possible combinations for example if there are five keys say 1, 2, 3, 4 , 5

I need to form all possible distinct combinations for example (1,2) , (1,3) , (1,2,3) , (2,3,4) etc
Can someone help me with an algorithm for this?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

What have you tried so far? Can you describe the process in English before trying to code it?

Hint: A HashMap's keySet() method returns a Set of keys.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9946
    
    6

Please dont' double post.


Never ascribe to malice that which can be adequately explained by stupidity.
Shruthi Babu
Ranch Hand

Joined: May 04, 2007
Posts: 54
I am trying to use the combination rule of "n!/r!(n-r)!" but here is the pbm according to this if I wanted all the combinations for a particular number of pairs eg all two pair values ... eg 1, 2, 3, 4 the outcome would be (1,2) , (2,3) , (3,4) , (1,3) (1,4) , (2,4)

but I need all possible pairs say all 2 pairs, 3 pairs , 4 pairs etc... is it a good way to wrap it with a loop and pass the "r" value for each loop or is there a way to figure this out. Any help is highly appreciated.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9946
    
    6

if the order doesn't matter (i.e. (1,2) is the same as (2,1)), it's pretty simple. count from 0 to 2^(number of elements) - 1. Then, use a bit mask to figure out which to include.

in other words, assuming 3 elements:

[ May 22, 2007: Message edited by: Fred Rosenberger ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Iterating the hash map to form combinations
 
Similar Threads
iterating the hash map to form combinations
Valentine's Ideas - Who's doing what?
Using both xs:sequence and xs:all
Printing out the combinations of a given string
Behaviour on failure of validate in form bean