fork(5) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. // The main function that prints all combinations of size r
  12. // in arr[] of size n. This function mainly uses combinationUtil()
  13. static void printCombination(String arr[], int n, int r)
  14. {
  15. // A temporary array to store all combination one by one
  16. String[] data = new String[r];
  17.  
  18. // Print all combination using temprary array 'data[]'
  19. combinationUtil(arr, data, 0, n-1, 0, r);
  20. }
  21.  
  22. /* arr[] ---> Input Array
  23.   data[] ---> Temporary array to store current combination
  24.   start & end ---> Staring and Ending indexes in arr[]
  25.   index ---> Current index in data[]
  26.   r ---> Size of a combination to be printed */
  27. static void combinationUtil(String arr[], String data[], int start, int end, int index, int r)
  28. {
  29. // Current combination is ready to be printed, print it
  30. if (index == r)
  31. {
  32. for (int j=0; j<r; j++)
  33. System.out.printf("%s ", data[j]);
  34. System.out.printf("\n");
  35. return;
  36. }
  37.  
  38. // replace index with all possible elements. The condition
  39. // "end-i+1 >= r-index" makes sure that including one element
  40. // at index will make a combination with remaining elements
  41. // at remaining positions
  42. for (int i=start; i<=end && end-i+1 >= r-index; i++)
  43. {
  44. data[index] = arr[i];
  45. combinationUtil(arr, data, i+1, end, index+1, r);
  46. }
  47. }
  48. public static void main (String[] args) throws java.lang.Exception
  49. {
  50. // Driver program to test above functions
  51. String arr[] = {"A","B","C","D","E","F","G"};
  52. int r = 3;
  53. int n = arr.length;
  54. printCombination(arr, n, r);
  55. }
  56. }
Success #stdin #stdout 0.09s 380160KB
stdin
Standard input is empty
stdout
A B C 
A B D 
A B E 
A B F 
A B G 
A C D 
A C E 
A C F 
A C G 
A D E 
A D F 
A D G 
A E F 
A E G 
A F G 
B C D 
B C E 
B C F 
B C G 
B D E 
B D F 
B D G 
B E F 
B E G 
B F G 
C D E 
C D F 
C D G 
C E F 
C E G 
C F G 
D E F 
D E G 
D F G 
E F G