Skip to content

Instantly share code, notes, and snippets.

@ulisseslima
Last active August 23, 2022 22:24
Show Gist options
  • Save ulisseslima/26b9ffb2994a889b33b4033ee5a11ceb to your computer and use it in GitHub Desktop.
Save ulisseslima/26b9ffb2994a889b33b4033ee5a11ceb to your computer and use it in GitHub Desktop.
Combination table generator for java
package com.dvlcube.generators;
import java.util.HashSet;
import java.util.Set;
/**
* Combination table generator for java, inspired by:
* https://stackoverflow.com/questions/10723168/generating-truth-tables-in-java/10761325
*
* @since 25 de jan de 2022
* @author ulisses
*/
public class CombinationTable {
private final String[] options;
private final String[] combinations;
private boolean repetition = true;
/**
* @param options
* header
* @param combinations
* table
* @param repetition
* allow repetitions
* @since 25 de jan de 2022
*/
public CombinationTable(String[] options, String[] combinations, boolean repetition) {
this.options = options;
this.combinations = combinations;
this.repetition = repetition;
}
public static void main(String args[]) {
String[] options = System.getProperty("options", "A,B").split(",");
String[] combinations = System.getProperty("combinations", "0,1").split(",");
boolean repetition = Boolean.parseBoolean(System.getProperty("repetition", "true"));
CombinationTable table = new CombinationTable(options, combinations, repetition);
table.print();
}
public void print() {
StringBuilder header = new StringBuilder();
for (String op : options) {
header.append(" | " + op);
}
header.append("\n");
for (String op : options) {
header.append(" | " + op.replaceAll(".", "-"));
}
System.out.println(header);
generate(0, options, combinations, new String[options.length]);
}
/**
* @param index
* recursion control.
* @param options
* options to choose from. Defined once and only passed on when
* recursing.
* @param combinations
* number of combinations for each option. Defined once and only
* passed on when recursing.
* @param current
* starts with an empty array with options size; stores the current
* values, updated during recursion.
* @since 25 de jan de 2022
* @author ulisses
*/
public void generate(int index, String[] options, String[] combinations, String[] current) {
int optionsSize = options.length;
int combinationsSize = combinations.length;
if (index == optionsSize) { // generated a full "solution"
if (!repetition) {
Set<String> set = new HashSet<>();
for (int i = 0; i < optionsSize; i++) {
set.add(current[i]);
}
if (set.size() < current.length) {
return;
}
}
for (int i = 0; i < optionsSize; i++) {
System.out.print(" | " + current[i]);
}
System.out.println();
} else {
for (int i = 0; i < combinationsSize; i++) {
current[index] = combinations[i];
generate(index + 1, options, combinations, current);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment