有没有一种操作可以检查多个变量并输出结果?

huangapple go评论64阅读模式
英文:

Is there a operation that checks multiple variables for an output?

问题

要进一步解释,我想创建一个选项树,用于检查多个变量。例如,它会检查3个名为 abc 的布尔变量。

(true, true, true) 将输出一个数字
(true, true, false) 将输出另一个数字
(true, false, true) 将输出另一个不同的数字
(true, false, false) 将输出另一个不同的新数字
以此类推...

字典、if语句、列表和switch语句都是选项,但使用它们将需要指数级更多的时间来添加另一个要检查的变量。

那么是否有一种操作可以简化这个过程?

英文:

To further explain, I want to create a tree of options that checks multiple variables. For example, it checks 3 boolean variables named, a, b and c.

(true, true, true) would output a number
(true, true, false) would output another number
(true, false, true) would output another different number
(true, false, false) would output another different new number
etc...

Dictionaries, if statements, lists, and switch statements are options but using those it would take exponentially more time to add another variable to check.

So is there an operation that streamlines this?

答案1

得分: 1

只针对这3个布尔变量:

(a ? 4 : 0) | (b ? 2 : 0) | (c ? 1 : 0)

为了推广到一组布尔变量的情况:

int result = 0;
for (boolean b : bs) {
  result = (result << 1) | (b ? 1 : 0);
}
英文:

For just those 3 boolean variables:

(a ? 4 : 0) | (b ? 2 : 0) | (c ? 1 : 0)

To generalize to an array of boolean variables:

int result = 0;
for (boolean b : bs) {
  result = (result &lt;&lt; 1) | (b ? 1 : 0);
}

huangapple
  • 本文由 发表于 2020年7月23日 07:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63044715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定