当前位置 : 主页 > 编程语言 > delphi >

单独评估多个布尔条件,只有一个可以为真(Delphi)

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有一个函数,它评估多个(在我的情况下为7)布尔变量和条件,如果只有其中一个为true,则结果为true(当然其余为假).我有以下代码: function GetExclusiveTrue: boolean;begin Result:= ( Integer(BoolVar1)
我有一个函数,它评估多个(在我的情况下为7)布尔变量和条件,如果只有其中一个为true,则结果为true(当然其余为假).我有以下代码:

function GetExclusiveTrue: boolean;
begin
  Result:= (
    Integer(BoolVar1) + 
    Integer(BoolVar2) + 
    Integer(BoolFunc3) + 
    Integer(BoolVar4) + 
    Integer(BoolFunc5) + 
    Integer(BoolVar6) + 
    Integer(BoolVar7)) = 1;
end;

我只是想知道是否有比这更好的解决方案?

PS:我想我没有正确定义我的问题是什么.

我正在寻找仅使用逻辑运算符的解决方案,不涉及任何转换.

PS2:看起来我无法正确解释我在寻找什么.我希望看到没有迭代,选择,函数调用等的解决方案.只允许布尔运算符.为什么?我只是想知道这是否可能.寻找逻辑运算的组合,其提供与上述函数相同的结果.

I want to see a solution without iteration, selection, function calls, etc. ONLY boolean operators allowed. Why? I just want to know if that is possible or not. Looking for a combination of logical operations which provides the same result as the function above.

您希望仅使用逻辑和/或xor和not运算符来实现此功能.这是这样的:

Result :=
     (b1 and not (b2 or b3 or b4))
  or (b2 and not (b1 or b3 or b4))
  or (b3 and not (b1 or b2 or b4))
  or (b4 and not (b1 or b2 or b3));

我给出了一个只有四个布尔值的例子,但任何数字的概念都是相同的.

网友评论