GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Java/java-combinations/Combination.java at master · TheophilePACE/Java Expand file tree/ Copy pathCombination.javaMore file actions 102 lines (77 loc) · 1.95 KB / Copy pathCombination.javaFile metadata and controls102 lines (77 loc) · 1.95 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 package com.hmkcode.baloot; public class Combination { public static void main(String[] args){ Object[] elements = new Object[] {'A','B','C','D','E', 'F', 'G', 'H'}; combination(elements,7); } public static void combination(Object[] elements, int K){ // get the length of the array // e.g. for {'A','B','C','D'} => N = 4 int N = elements.length; if(K > N){ System.out.println("Invalid input, K > N"); return; } // calculate the possible combinations // e.g. c(4,2) c(N,K); // get the combination by index // e.g. 01 --> AB , 23 --> CD int combination[] = new int[K]; // position of current index // if (r = 1) r* // index ==> 0 | 1 | 2 // element ==> A | B | C int r = 0; int index = 0; while(r >= 0){ // possible indexes for 1st position "r=0" are "0,1,2" --> "A,B,C" // possible indexes for 2nd position "r=1" are "1,2,3" --> "B,C,D" // for r = 0 ==> index < (4+ (0 - 2)) = 2 if(index <= (N + (r - K))){ combination[r] = index; // if we are at the last position print and increase the index if(r == K-1){ //do something with the combination e.g. add to list or print print(combination, elements); index++; } else{ // select index for next position index = combination[r]+1; r++; } } else{ r--; if(r > 0) index = combination[r]+1; else index = combination[0]+1; } } } public static int c(int n, int r){ int nf=fact(n); int rf=fact(r); int nrf=fact(n-r); int npr=nf/nrf; int ncr=npr/rf; System.out.println("C("+n+","+r+") = "+ ncr); return ncr; } public static int fact(int n) { if(n == 0) return 1; else return n * fact(n-1); } public static void print(int[] combination, Object[] elements){ String output = ""; for(int z = 0 ; z < combination.length;z++){ output += elements[combination[z]]; } System.out.println(output); } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |