Reputation: 23
Assume that the array foo consists of alternating value, index at 0 = true, 1 = false, 2 = true, etc. Ex:
for (int index = 0; index < foo.length; index++)
I'm trying to find a way to complete this code by only using one statement. So far the only idea I have is:
foo[index] = !index--; // I want it to check the last Boolean of index, and reverse it
This is of course bad code and doesn't exist, but is there a way to alternate and have it look like something like this:
foo[index] = (code that goes in here);
Upvotes: 2
Views: 1577
Reputation: 509
for (int index = 0; index < foo.length; index++)
foo[index]=!foo[index];
is optimized but, If you want complex, you can try this too.
for (int index = foo.length-1; index >0; index--)
foo[index]=foo[(index+1)%2];foo[index]=!foo[index];
Upvotes: -1
Reputation: 8587
Since boolean arrays are initially all false.
boolean [] foo = new boolean[100];
for (int i = 0; i < foo.length; i+=2)
foo[i] = true;
Upvotes: 4
Reputation: 522226
One way to do this is iterate with a loop up to some maximum value and then use the modulus to determine the boolean value:
boolean array = new boolean[foo.length];
for (int index = 0; index < foo.length; index++) {
array[i] = index % 2 == 0;
}
Upvotes: 0
Reputation: 726849
You can use bit operations or modulo division:
foo[index] = (index & 1) == 0;
or
foo[index] = (index % 2) == 0;
Upvotes: 3