假设我传入 3 个 true 和 5 个 false,我如何编写
getAllCombos
方法来返回一个包含以下内容的列表:
SampleForSO
对象,其中选择了 3 个SampleForSO
对象所以我会返回一个列表:
公共类 SampleForSO {
private boolean b0;
private boolean b1;
private boolean b2;
private boolean b3;
private boolean b4;
private boolean b5;
private boolean b6;
private boolean b7;
public SampleForSO(boolean b0, boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6, boolean b7) {
this.b0 = b0;
this.b1 = b1;
this.b2 = b2;
this.b3 = b3;
this.b4 = b4;
this.b5 = b5;
this.b6 = b6;
this.b7 = b7;
}
public boolean equals(Object o) {
if(o instanceof SampleForSO) {
SampleForSO outer = (SampleForSO) o;
return outer.b0 == this.b0 && outer.b1 == this.b1 && outer.b2 == this.b2 && outer.b3 == this.b3 && outer.b4 == this.b4 && outer.b5 == this.b5 && outer.b6 == this.b6 && outer.b7 == this.b7;
}
return false;
}
public static List<SampleForSO> getAllCombos(boolean b0, boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6, boolean b7){
// How to get all the combos?
return new ArrayList<SampleForSO>();
}
}
public class SampleForSOTest {
public SampleForSOTest() {
super();
}
@Test
public void testGetAllCombinations() throws Exception {
// 3 true, 5 false, but need this to work for all possibilities
boolean b0_ = true;
boolean b1_ = true;
boolean b2_ = true;
boolean b3_ = false;
boolean b4_ = false;
boolean b5_ = false;
boolean b6_ = false;
boolean b7_ = false;
int numCombosWithAllThree = 1;
int numCombosWithTwo = 3;
int numCombosWithOne = 3;
int numCombosWithZero = 1;
int expectedSize = numCombosWithAllThree + numCombosWithTwo + numCombosWithOne + numCombosWithZero;
List<SampleForSO> allCombos = SampleForSO.getAllCombos(b0_, b1_, b2_, b3_, b4_, b5_, b6_, b7_);
assertEquals(expectedSize, allCombos.size());
}
}
我想要的组合是:
public static List<List<Boolean>> generateAll(ArrayList<Boolean> input) {
List<List<Boolean>> combinations = new ArrayList<>();
combinations.add(new ArrayList<>());
for (Boolean inputIndexValue : input) {
List<List<Boolean>> newCombinations = new ArrayList<>();
for (List<Boolean> indexCombination : combinations) {
if (inputIndexValue) {
List<Boolean> newCombination = new ArrayList<>(indexCombination);
newCombination.add(false);
newCombinations.add(newCombination);
}
indexCombination.add(inputIndexValue);
}
combinations.addAll(newCombinations);
}
return combinations;
}
public static void main(String[] args) {
ArrayList<Boolean> input = new ArrayList<>();
input.add(true);
input.add(true);
input.add(true);
input.add(false);
input.add(false);
input.add(false);
input.add(false);
input.add(false);
List<List<Boolean>> result = generateAll(input);
for (List<Boolean> innerArray : result) {
System.out.println(innerArray);
}
}