|
| 1 | +package com.hmkcode; |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +public class ForwardBackward { |
| 6 | + |
| 7 | + |
| 8 | + public static void main(String[] args){ |
| 9 | + Object[] elements = new Object[] {'A','B','C','D','E'}; |
| 10 | + combination(elements,3); |
| 11 | + } |
| 12 | + |
| 13 | + |
| 14 | + public static void combination(Object[] elements, int K){ |
| 15 | + |
| 16 | + // get the length of the array |
| 17 | + // e.g. for {'A','B','C','D'} => N = 4 |
| 18 | + int N = elements.length; |
| 19 | + |
| 20 | + if(K > N){ |
| 21 | + System.out.println("Invalid input, K > N"); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // calculate the possible combinations |
| 26 | + c(N,K); |
| 27 | + |
| 28 | + // init combination index array |
| 29 | + int pointers[] = new int[K]; |
| 30 | + |
| 31 | + |
| 32 | + int r = 0; // index for combination array |
| 33 | + int i = 0; // index for elements array |
| 34 | + |
| 35 | + while(r >= 0){ |
| 36 | + |
| 37 | + // forward step if i < (N + (r-K)) |
| 38 | + if(i <= (N + (r - K))){ |
| 39 | + pointers[r] = i; |
| 40 | + |
| 41 | + // if combination array is full print and increment i; |
| 42 | + if(r == K-1){ |
| 43 | + print(pointers, elements); |
| 44 | + i++; |
| 45 | + } |
| 46 | + else{ |
| 47 | + // if combination is not full yet, select next element |
| 48 | + i = pointers[r]+1; |
| 49 | + r++; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // backward step |
| 54 | + else{ |
| 55 | + r--; |
| 56 | + if(r >= 0) |
| 57 | + i = pointers[r]+1; |
| 58 | + |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + private static int c(int n, int r){ |
| 66 | + int nf=fact(n); |
| 67 | + int rf=fact(r); |
| 68 | + int nrf=fact(n-r); |
| 69 | + int npr=nf/nrf; |
| 70 | + int ncr=npr/rf; |
| 71 | + |
| 72 | + System.out.println("C("+n+","+r+") = "+ ncr); |
| 73 | + |
| 74 | + return ncr; |
| 75 | + } |
| 76 | + |
| 77 | + private static int fact(int n) |
| 78 | + { |
| 79 | + if(n == 0) |
| 80 | + return 1; |
| 81 | + else |
| 82 | + return n * fact(n-1); |
| 83 | + } |
| 84 | + |
| 85 | + |
| 86 | + private static void print(int[] combination, Object[] elements){ |
| 87 | + |
| 88 | + String output = ""; |
| 89 | + for(int z = 0 ; z < combination.length;z++){ |
| 90 | + output += elements[combination[z]]; |
| 91 | + } |
| 92 | + System.out.println(output); |
| 93 | + } |
| 94 | +} |
0 commit comments