| 12
 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
 
 | package tianma.exercise;
 public class Combination {
 
 
 private int globalCounter = 0;
 
 private int validCounter = 0;
 
 
 
 
 public void combineUnrepeatable(int[] input, int m, int threshold) {
 combine(input, m, threshold, false);
 }
 
 
 
 
 public void combineRepeatable(int[] input, int m, int threshold) {
 combine(input, m, threshold, true);
 }
 
 private void combine(int[] input, int m, int threshold, boolean repeatable) {
 if (input == null || input.length == 0 || m <= 0 || m > input.length) {
 throw new RuntimeException("参数错误");
 }
 int[] out = new int[m];
 innerCombine(input, m, 0, out, 0, threshold, repeatable);
 float ratio = 1.0f * validCounter / globalCounter;
 System.out.println("总次数 = " + globalCounter + ", 小于 " + threshold + "的命中次数 = " + validCounter + ", 命中率 = " + ratio);
 globalCounter = validCounter = 0;
 }
 
 private void innerCombine(int[] input, int m, int beginIdx, int[] out, int index, int threshold, boolean repeatable) {
 if (m == 0) {
 int total = 0;
 for (int i = 0; i < index; i++) {
 System.out.print(out[i] + " ");
 total += out[i];
 }
 if (total < threshold) {
 validCounter++;
 System.out.print("*");
 }
 globalCounter++;
 System.out.println();
 return;
 }
 
 for (int i = repeatable ? 0 : beginIdx; i < input.length; i++) {
 out[index] = input[i];
 innerCombine(input, m - 1, i + 1, out, index + 1, threshold, repeatable);
 }
 
 }
 
 public static void main(String[] args) {
 
 int[] in = { 0, 0, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 7, 7, 7, 10 };
 int m = 3;
 int threshold = 11;
 boolean repeatable = true;
 Combination combination = new Combination();
 combination.combine(in, m, threshold, repeatable);
 }
 }
 
 |