Christian Christian - 2 months ago 7
Java Question

Generating the combinations of a "choose" operation

I want to perform a variation of a "6 choose 2" operation. I have written the following code.

public void choosePatterns(){
String[] data = {"1", "2", "3", "4", "5", "6"};
String[] originalPattern = new String[15];
int index = 0;
for(int i = 0; i < (6-1); i++)
{
for(int j = i+1; j < 6; j++)
{
System.out.println(i + "," +j);
}
}
}


My code so far generates all the possible combinations of "6 choose 2." However, I would like to vary this and print all the remaining numbers. So far instance, if one of the combinations of "6 choose 2" is "3" and "4," then I would like to print "1," "2," "5," "6."

I am not sure how to most efficiently do this. The long-winded way would be to delete those indices in the "data" array, shift the data so there aren't gaps, then print the array. But is there a faster, more efficient way to do this?

mab mab
Answer

Here's a way to do it.

public static void choosePatterns(int total, int toChoose) {
  List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer.valueOf(0)).collect(Collectors.toList());
  resetIndex(indices, 0, 1, total);
  while (true) {
    System.out.println("chosen: " + indices);
    System.out.print("not chosen: ");
    for (int i = 1; i <= total; i++) {
      if (! indices.contains(Integer.valueOf(i))) {
        System.out.print(i + " ");
      }
    }
    System.out.println("\n");

    if (! incrementIndices(indices, indices.size() - 1, total)) {
      break;
    }
  }
}

public static boolean resetIndex(List<Integer> indices, int posn, int value, int total) {
  if (value <= total) {
    indices.set(posn, value);
    return posn == indices.size() - 1 ? true : resetIndex(indices, posn + 1, value + 1, total);
  } else {
    return false;
  }
}

public static boolean incrementIndices(List<Integer> indices, int posn, int total) {
  if (indices.get(posn) < total) {
    indices.set(posn, indices.get(posn) + 1);
  } else {
    int resetPosn = posn;
    do {
      if (resetPosn-- == 0) return false;
    } while (! resetIndex(indices, resetPosn, indices.get(resetPosn) + 1, total));
  }
  return true;
}

public static void main(String[] args) throws IOException {
  choosePatterns(6, 2);
}

It prints this:

chosen: [1, 2]
not chosen: 3 4 5 6 

chosen: [1, 3]
not chosen: 2 4 5 6 

chosen: [1, 4]
not chosen: 2 3 5 6 

chosen: [1, 5]
not chosen: 2 3 4 6 

chosen: [1, 6]
not chosen: 2 3 4 5 

chosen: [2, 3]
not chosen: 1 4 5 6 

chosen: [2, 4]
not chosen: 1 3 5 6 

chosen: [2, 5]
not chosen: 1 3 4 6 

chosen: [2, 6]
not chosen: 1 3 4 5 

chosen: [3, 4]
not chosen: 1 2 5 6 

chosen: [3, 5]
not chosen: 1 2 4 6 

chosen: [3, 6]
not chosen: 1 2 4 5 

chosen: [4, 5]
not chosen: 1 2 3 6 

chosen: [4, 6]
not chosen: 1 2 3 5 

chosen: [5, 6]
not chosen: 1 2 3 4