Advertisement
vladimirVenkov

Combinations

Jun 18th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. public class Combinations {
  6.     public static void main(String[] args) throws IOException {
  7.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  8.  
  9.         char arr[] = {'a', 'b', 'a', 'c'};
  10. //        char arr[] = {'0', '1','2'};
  11.         int r = 3;
  12.         int n = arr.length;
  13.         printCombination(arr, n, r);
  14.  
  15.     }
  16.     /* arr[]  ---> Input Array
  17.     data[] ---> Temporary array to store current combination
  18.     start & end ---> Staring and Ending indexes in arr[]
  19.     index  ---> Current index in data[]
  20.     r ---> Size of a combination to be printed */
  21.     static void combinationUtil(char arr[], char data[], int start,
  22.                                 int end, int index, int r)
  23.     {
  24.         // Current combination is ready to be printed, print it
  25.         if (index == r)
  26.         {
  27.             for (int j=0; j<r; j++)
  28.                 System.out.print(data[j]+" ");
  29.             System.out.println("");
  30.             return;
  31.         }
  32.  
  33.         // replace index with all possible elements. The condition
  34.         // "end-i+1 >= r-index" makes sure that including one element
  35.         // at index will make a combination with remaining elements
  36.         // at remaining positions
  37.         for (int i = start; i <= end && end - i + 1 >= r - index; i++)
  38.         {
  39.             data[index] = arr[i];
  40.             combinationUtil(arr, data, i + 1, end, index + 1, r);
  41.         }
  42.     }
  43.  
  44.     // The main function that prints all combinations of size r
  45.     // in arr[] of size n. This function mainly uses combinationUtil()
  46.     static void printCombination(char arr[], int n, int r)
  47.     {
  48.         // A temporary array to store all combination one by one
  49.         char data[]=new char[r];
  50.  
  51.         // Print all combination using temprary array 'data[]'
  52.         combinationUtil(arr, data, 0, n - 1, 0, r);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement