File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to generate the combinations Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How to generate the combinations" Watch "How to generate the combinations" New topic
Author

How to generate the combinations

James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 577

I am struck with a problem...
I need to write a program which should pick up 'n' elements from 'n' number of arrays, but only one from each array at a time.( all combination)
Hope i am clear.
i.e
I don't know how many arrays are present and what is the size of each array . I would come to know about the number and size of the array during the execution time.
Once i know the required data, i need to generate all the combination.
EX:
ARRAY 1: 1,2,3
ARRAY 2 : 4,5,6,7
ARRAY 3: 8,9

So the output should be :
1,4,8
1,4,9
1,5,8
...
....


Somebody please guide me

SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 13396

Somebody please guide me


I am assuming that you just learned about recursion. You should review that a bit -- as that is the technique that will solve this problem.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12612
Seems pretty straight-forward using recursion; what have you come up with so far?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 8104

i see Henry has beat me to it AGAIN...

But here's another hint along his lines. This problem would be easy if you already had every possible combination for the sets 1 through n-1 (call this a 'Superset' S). Then all you'd have to do is get each element in turn from set N, and combine it with every element in S.

in other words, if you had

a = 1,2
b = 3,4
c = 5

if you could get the set with { {3,5}, {4,5} } (everything from just sets b and c), take each element in turn from a and add it to this set... so add '1' to all these giving { {1,3,5}, {1,4,5} } (but leave the original set alone), and save these off somewhere

then add '2' to each element, giving { {2,3,5}, {2,4,5} }, and add those to where you saved off your '1' elements, giving you:

{ {1,3,5}, {1,4,5}, {2,3,5}, {2,4,5} }

and you're done.


Never ascribe to malice that which can be adequately explained by stupidity.
 
 
subject: How to generate the combinations
 
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com