Ralph
Ralph

Reputation: 23

Java: Alternating Boolean values in an array

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

Answers (5)

Amrendra
Amrendra

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

xiaofeng.li
xiaofeng.li

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

Tim Biegeleisen
Tim Biegeleisen

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

Fadi Banna
Fadi Banna

Reputation: 554

Something like this should work:

Foo[index] = (index%2==0) 

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

You can use bit operations or modulo division:

foo[index] = (index & 1) == 0;

or

foo[index] = (index % 2) == 0;

Upvotes: 3

Related Questions