[英]Code that return True if only one or two of three params are true
如果只有三個參數中的一個或兩個是真的,我需要一個返回True的代碼
什么是最短/最好的方式?
我沉迷於這個問題!
bool MyFourthAnswer(bool a, bool b, bool c)
{
return (a != b) || (b != c);
}
只需檢查是否至少設置了其中一個值, 而不是設置了所有三個值:
bool result = (a | b | c) & !(a & b & c);
這是一種奇特的方式:
bool oneOrTwoTrue = a ? (!b || !c) : (b || c);
如果設置了第一個bool,則應該取消其中任何一個。 否則,應設置剩余的任何一個。
編輯 - 回應評論:在生產代碼中,我可能會選擇@ AS-CII或@Stuart; 它最清楚地傳達了計算內容的意圖。
這應該做到這一點
return !((a & b & c) || (!a & !b & !c))
另一個答案......我喜歡這個問題......
bool MyThirdAnswer(params bool[] list)
{
return list.Distinct().Count() == 2;
}
LINQ方式:
bool[] params = { true, false, true };
int count = params.Count(a => a);
bool result = count == 2 || count == 1;
我的最終答案......誠實!
我想到的一個問題是,這是否真的應該使用3個bool。
使用[Flags]枚舉可能更合適,而不是使用3個bool - 它可能使代碼更快,更易讀,更實用。
這個代碼可能是:
[flags]
enum Alarm
{
None = 0x0,
Kitchen = 0x1,
Bathroom = 0x2,
Bedroom = 0x4,
All = Kitchen | Bathroom | Bedroom,
}
bool MyFifthAnswer(Alarm alarmState)
{
switch (alarmState)
{
case Alarm.None:
case Alarm.All:
return false;
default:
return true;
}
}
出於興趣,原問題中的3個bool是什么?
只是為了好玩,如果true = 1且false = 0:
return (a + b + c) % 3
另一個,假設false = 0且true =任何嚴格正整數:
return (a*b + b*c + c*a) > (3*a*b*c)
當你可以進行6次乘法並使其完全模糊時,為什么堅持使用幾個比較/布爾運算? ;-)
bool MyAnswer(params bool[] list)
{
var countTrue = list.Where(x => x).Count();
return countTrue == 1 || countTrue == 2;
}
編輯:經過評論者的誹謗后, true == x
被刪除...對不起 - 這是我必須遵循的“編碼標准”文件!
這是一個非常有趣的問題 - 我必須在Clojure(我正在學習的一種語言)中嘗試它
(defn one-or-two-args-true? [& args]
(> 3 (count (filter true? args)) 0))
user=> (one-or-two-args-true? false false false)
false
user=> (one-or-two-args-true? false false true)
true
user=> (one-or-two-args-true? false true true)
true
user=> (one-or-two-args-true? true true true)
false
由於我之前的回答太長,我會再試一次:
bool MySecondAnswer(params bool[] list)
{
return list.GroupBy(x => x).Count() == 2;
}
bash中有69個字符
x (){ test "$(echo $@|sed 's/ /\n/g'|sort|uniq|grep -c .)" == "2"; }
python中有32個字符
def x(a,b,c):return a!=b or b!=c
將布爾值放在列表中,然后使用linq進行過濾:
var options = new List<bool>() { true, true, false };
var trueOptions = options.Where( opt => opt };
var count = trueOptions.Count();
return count == 1 || count == 2;
bool result = !(a && b && c) && (a || b || c)
好問題
我的答案:
return (a||b||c) != (a&&b&&c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.