当只有一个条件为true时,如何使条件语句返回true



我需要实现一个功能,该功能以布尔值列表作为输入,并且只有当其中一个条件为true时才返回true(如果更多,则返回false(。更正式地说,f(c1, c2, c3 ... cN)返回true当且仅当只有一个条件计算结果为true,否则返回false。

我实现了这个方法,

boolean trueOnce(boolean[] conditions) {
boolean retval = false;
for (boolean c: conditions) {
if (c) {
if (!retval) {
retval = true;
} else {
retval = false;
break;
}
}
}
return retval;
}

但我要求一些更实用的东西。我正在使用Java,但我认为这个问题对每种语言都是通用的。谢谢

编辑:上面的例子做得很好,我只是想找一个更实用的方法。

一个带有计数true存在的条件的简单循环是一种简单的方法。return语句是返回boolean的比较,无论true计数是否等于1:

long count = 0;
for (boolean condition: conditions) {
if (condition) {
count++;
}
}
return count == 1;

这总是迭代所有数组,而这些数组并不总是必需的。当找到两个true值时,可以优化迭代以停止,因此继续迭代没有意义。

long count = 0;
for (boolean condition: conditions) {
if (condition && ++count > 1) {
break;
}
}
return count == 1;

您可以使用此解决方案

public boolean trueOnce(boolean[] conditions) {
boolean m = false;
for(boolean condition : conditions) {
if(m && condition)
return false;
m |= condition;
}
return m;
}

这是一个非常小的解决方案,只需几行即可完成您想要的操作。

使用Java Stream API:

boolean trueOnce(boolean[] conditions) {
return IntStream.range(0, conditions.length)
.filter(x -> conditions[x])  // leave only `true` values
.limit(2)             // no need to get more than two
.count() == 1;        // check if there is only one `true` value
}

可以使用while运算符执行迭代。定义了一个变量来控制正值的增量,另一个变量用于计算数组的每个元素。这两个变量将是我们的停止条件,该方法将返回解决方案,当存在单个正值时为true,而在所有其他情况下为false。

boolean trueOnce(boolean[] conditions) 
{
int i = 0, count = 0;

while(count <= 1 && i < conditions.length){
if(conditions[i++]){
count++;
}
}

return count == 1;
}

或者按照建议,我们可以使用:

private static boolean trueOnce(boolean[] conditions) 
{
int count = 0;

for(int i = 0; i < conditions.length && count <= 1; i++){
if(conditions[i]){
count++;
}
}

return count == 1;
}

使用Stream API,您可以将其重写为(尽管它看起来不像普通循环那样"实用"(:

import java.util.stream.*;
static boolean trueOnce(boolean ... conditions) {
// find index of first true, if not available get -1
int firstTrue = IntStream.range(0, conditions.length)
.filter(i -> conditions[i])
.findFirst().orElse(-1);
// if first true is found, check if none in the remainder of array is true
return firstTrue > -1 && IntStream.range(firstTrue + 1, conditions.length)
.noneMatch(i -> conditions[i]);
}

使用@VLAZ:建议的更改恢复初始版本

import java.util.stream.*;
boolean trueOnce(boolean[] conditions) {
return IntStream.range(0, conditions.length)
.filter(i -> conditions[i])
.limit(2) // !
.count() == 1;
}

最新更新