没有类型转换,如何确定"*完全"一个布尔值是否正确? [英] How do I determine if *exactly* one boolean is true, without type conversion?

查看:91
本文介绍了没有类型转换,如何确定"*完全"一个布尔值是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个任意的布尔值列表,最精确地确定其中一个 正确的方法是什么?

最明显的技巧是类型转换:将它们转换为 0 表示 false1 表示 true 和然后将它们求和,并返回 sum == 1 .

我想知道是否有一种方法无需将它们转换为整数,实际上是使用布尔逻辑的.

(这似乎应该是琐碎的,idk,漫长的一周)

:如果不那么明显,这更多的是代码问题/理论问题.我对在PROD代码中使用类型转换/int加法不感到困惑,我只是想知道是否有没有这样做的方法.

Edit2 :抱歉,这是一个漫长的一周,我对自己的解释不佳.让我试试这个:

在布尔逻辑中,如果所有布尔都为真,则对布尔值的集合进行与"运算,如果其中至少一个为真,则对集合进行或"运算.如果正好一个布尔值是真的,是否存在一个逻辑构造将是真的?例如,XOR是用于两个布尔值的集合,但不限于此,它会落空.

解决方案

使用简单的布尔逻辑,可能无法实现您想要的.因为您要的是对真值的评估,不仅基于真值,而且还基于其他信息(在这种情况下为计数).但是布尔值评估是二进制逻辑,除了操作数本身,它不能依赖于其他任何东西.而且,由于存在四种可能的操作数组合,但只有两个结果,因此无法进行逆向工程来找到给定真值的操作数.给定一个错误,你能告诉你是因为 F ^ F 还是 T ^ T 在你的情况下,以便根据它确定下一个评估?

Given an arbitrary list of booleans, what is the most elegant way of determining that exactly one of them is true?

The most obvious hack is type conversion: converting them to 0 for false and 1 for true and then summing them, and returning sum == 1.

I'd like to know if there is a way to do this without converting them to ints, actually using boolean logic.

(This seems like it should be trivial, idk, long week)

Edit: In case it wasn't obvious, this is more of a code-golf / theoretical question. I'm not fussed about using type conversion / int addition in PROD code, I'm just interested if there is way of doing it without that.

Edit2: Sorry folks it's a long week and I'm not explaining myself well. Let me try this:

In boolean logic, ANDing a collection of booleans is true if all of the booleans are true, ORing the collection is true if least one of them is true. Is there a logical construct that will be true if exactly one boolean is true? XOR is this for a collection of two booleans for example, but any more than that and it falls over.

解决方案

With plain boolean logic, it may not be possible to achieve what you want. Because what you are asking for is a truth evaluation not just based on the truth values but also on additional information(count in this case). But boolean evaluation is binary logic, it cannot depend on anything else but on the operands themselves. And there is no way to reverse engineer to find the operands given a truth value because there can be four possible combinations of operands but only two results. Given a false, can you tell if it is because of F ^ F or T ^ T in your case, so that the next evaluation can be determined based on that?.

这篇关于没有类型转换,如何确定"*完全"一个布尔值是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆