According to your example I'm printing combinations:
public class PrintCombinations {
public static void main( final String[] args ) {
// testing input 1
int n = 2;
char[] a = { 'a', 'b', 'v', 'f' };
solve( n, a );
// testing input 2
n = 3;
a = new char[] { '1', '2', '3', '4', '5' };
solve( n, a );
}
private static void solve( final int n, final char[] a ) {
final int[] selected = new int[n];
print( n, a, 0, selected );
}
// need to know how many items are selected - n, input array - a
// item which can be selected next - from and already selected items
private static void print( final int n, final char[] a, final int from, final int[] selected ) {
if ( n == 0 ) { // all selected, just print them
for ( int i = 0; i < selected.length; ++i ) {
System.out.print( a[ selected[ i ] ] + " " );
}
System.out.println();
return;
}
// select one and use recursion for others
for ( int i = from; i < a.length; ++i ) {
selected[ selected.length - n ] = i;
print( n - 1, a, i + 1, selected );
}
}
}
But you have to realize, that number of combinations is
, so it is quite big number for example
and printout 10 milions arrays will take a while...