|
| 1 | +package com.hmkcode.baloot; |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +public class Combination { |
| 6 | + |
| 7 | + |
| 8 | + public static void main(String[] args){ |
| 9 | + Object[] elements = new Object[] {'A','B','C','D','E', 'F', 'G', 'H'}; |
| 10 | + |
| 11 | + combination(elements,7); |
| 12 | + } |
| 13 | + |
| 14 | + |
| 15 | + public static void combination(Object[] elements, int K){ |
| 16 | + |
| 17 | + // get the length of the array |
| 18 | + // e.g. for {'A','B','C','D'} => N = 4 |
| 19 | + int N = elements.length; |
| 20 | + |
| 21 | + if(K > N){ |
| 22 | + System.out.println("Invalid input, K > N"); |
| 23 | + return; |
| 24 | + } |
| 25 | + // calculate the possible combinations |
| 26 | + // e.g. c(4,2) |
| 27 | + c(N,K); |
| 28 | + |
| 29 | + // get the combination by index |
| 30 | + // e.g. 01 --> AB , 23 --> CD |
| 31 | + int combination[] = new int[K]; |
| 32 | + |
| 33 | + // position of current index |
| 34 | + // if (r = 1) r* |
| 35 | + // index ==> 0 | 1 | 2 |
| 36 | + // element ==> A | B | C |
| 37 | + int r = 0; |
| 38 | + int index = 0; |
| 39 | + |
| 40 | + while(r >= 0){ |
| 41 | + // possible indexes for 1st position "r=0" are "0,1,2" --> "A,B,C" |
| 42 | + // possible indexes for 2nd position "r=1" are "1,2,3" --> "B,C,D" |
| 43 | + |
| 44 | + // for r = 0 ==> index < (4+ (0 - 2)) = 2 |
| 45 | + if(index <= (N + (r - K))){ |
| 46 | + combination[r] = index; |
| 47 | + |
| 48 | + // if we are at the last position print and increase the index |
| 49 | + if(r == K-1){ |
| 50 | + |
| 51 | + //do something with the combination e.g. add to list or print |
| 52 | + print(combination, elements); |
| 53 | + index++; |
| 54 | + } |
| 55 | + else{ |
| 56 | + // select index for next position |
| 57 | + index = combination[r]+1; |
| 58 | + r++; |
| 59 | + } |
| 60 | + } |
| 61 | + else{ |
| 62 | + r--; |
| 63 | + if(r > 0) |
| 64 | + index = combination[r]+1; |
| 65 | + else |
| 66 | + index = combination[0]+1; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + public static int c(int n, int r){ |
| 74 | + int nf=fact(n); |
| 75 | + int rf=fact(r); |
| 76 | + int nrf=fact(n-r); |
| 77 | + int npr=nf/nrf; |
| 78 | + int ncr=npr/rf; |
| 79 | + |
| 80 | + System.out.println("C("+n+","+r+") = "+ ncr); |
| 81 | + |
| 82 | + return ncr; |
| 83 | + } |
| 84 | + |
| 85 | + public static int fact(int n) |
| 86 | + { |
| 87 | + if(n == 0) |
| 88 | + return 1; |
| 89 | + else |
| 90 | + return n * fact(n-1); |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | + public static void print(int[] combination, Object[] elements){ |
| 95 | + |
| 96 | + String output = ""; |
| 97 | + for(int z = 0 ; z < combination.length;z++){ |
| 98 | + output += elements[combination[z]]; |
| 99 | + } |
| 100 | + System.out.println(output); |
| 101 | + } |
| 102 | +} |
0 commit comments