Java:数组中布尔值的交替

时间:2022-06-08 10:05:01

Assume that the array foo consists of alternating value, index at 0 = true, 1 = false, 2 = true, etc. Ex:

假设数组foo包含交替值,下标0 = true, 1 = false, 2 = true,等等。

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);

5 个解决方案

#1


4  

Since boolean arrays are initially all false.

因为布尔数组最初都是假的。

boolean [] foo = new boolean[100];
for (int i = 0; i < foo.length; i+=2)
    foo[i] = true;

#2


3  

You can use bit operations or modulo division:

您可以使用位操作或模块划分:

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

or

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

#3


0  

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;
}

#4


-1  

Something like this should work:

像这样的东西应该是有用的:

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

#5


-1  

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 = 0;指数< foo.length;(指数)指数+ +)foo = ! foo(指数);是优化的,但如果你想要复杂,你也可以试试。

for (int index = foo.length-1; index >0; index--) foo[index]=foo[(index+1)%2];foo[index]=!foo[index];

for (int index = foo.length-1;指数> 0;指数——)foo(指数)= foo[(指数+ 1)% 2];foo(指数)= ! foo(指数);

#1


4  

Since boolean arrays are initially all false.

因为布尔数组最初都是假的。

boolean [] foo = new boolean[100];
for (int i = 0; i < foo.length; i+=2)
    foo[i] = true;

#2


3  

You can use bit operations or modulo division:

您可以使用位操作或模块划分:

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

or

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

#3


0  

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;
}

#4


-1  

Something like this should work:

像这样的东西应该是有用的:

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

#5


-1  

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 = 0;指数< foo.length;(指数)指数+ +)foo = ! foo(指数);是优化的,但如果你想要复杂,你也可以试试。

for (int index = foo.length-1; index >0; index--) foo[index]=foo[(index+1)%2];foo[index]=!foo[index];

for (int index = foo.length-1;指数> 0;指数——)foo(指数)= foo[(指数+ 1)% 2];foo(指数)= ! foo(指数);