mtbc: maze I (white-red)
[personal profile] mtbc
I have Java methods taking Boolean arguments and I want to test every combination of those. To have our testing framework try those combinations I need to provide it with a two-dimensional array of the n-bit Boolean values. The code I once had is,
final Boolean[][] testArguments = new Boolean[1 << argCount][];
int testNum = 0;
testArguments[testNum] = new Boolean[argCount];
Arrays.fill(testArguments[testNum], false);
while (++testNum < testArguments.length) {
  testArguments[testNum] = Arrays.copyOf(testArguments[testNum - 1], argCount);
  int argNum = argCount - 1;
  while (true) {
    if (testArguments[testNum][argNum]) {
      testArguments[testNum][argNum--] = false;
    } else {
      testArguments[testNum][argNum] = true;
      break;
    }
  }
}
return testArguments;
I thought that was quite neat. However, with advances in both Java and Google's Guava one can now replace all that with,
return Lists.cartesianProduct(Collections.nCopies(argCount, ImmutableList.of(false, true)))
       .stream().map(args -> args.stream().toArray(Boolean[]::new)).toArray(Boolean[][]::new);
Admittedly I doubt that either is easily read.

Profile

mtbc: photograph of me (Default)
Mark T. B. Carroll

June 2025

S M T W T F S
1 2 34567
891011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 7th, 2025 03:32 pm
Powered by Dreamwidth Studios