如何确定 *exactly* 一个布尔值是否为真,无需类型转换? [英] How do I determine if *exactly* one boolean is true, without type conversion?

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

问题描述

给定一个任意的布尔值列表,确定完全其中一个为真的最优雅的方法是什么?

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

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

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.

(这似乎应该是微不足道的,idk,漫长的一周)

如果不是很明显,这更像是一个代码高尔夫/理论问题.我对在 PROD 代码中使用类型转换/int 添加并不大惊小怪,我只是感兴趣是否有办法做到这一点.

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:

在布尔逻辑中,如果所有布尔值都为真,则对一组布尔值进行与运算为真,如果其中至少一个为真,则对集合进行或运算为真.如果恰好一个布尔值为真,是否有一个逻辑结构为真?例如,XOR 是用于两个布尔值的集合,但除此之外,它就会失败.

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.

推荐答案

使用普通的布尔逻辑,可能无法实现您想要的.因为您要求的是不仅基于真值而且基于附加信息(在这种情况下为计数)的真值评估.但是布尔求值是二元逻辑,它不能依赖于其他任何东西,只能依赖于操作数本身.并且没有办法通过逆向工程来找到给定真值的操作数,因为可能有四种可能的操作数组合,但只有两种结果.给定一个假的,你能判断是因为你的情况是F ^ F还是T ^ T,以便根据它来确定下一个评估?.

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?.

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

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