[C#][LINQ]樂透頭獎、雙贏彩及安慰獎的寫生

這週Review年輕同事的程式,程式中需要將兩組序列作比對來決定輸入資料的去向,意外發現了同事使用LINQ All及Any判斷式不小心留下的小bug,簡單作樂透案例給同事看:

  • 判斷序列的"任何項目"是否"都"符合(頭獎)
  • 判斷序列的"任何項目"是否都不符合(雙贏彩)
  • 判斷序列的任一項目是否符合(安慰獎)

 

只要開始投注,就會有三個結果:

 

測試案例共有4組,依序為全不中、全中及部分中獎。

new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 }
new List<int> { 1, 2, 3 }, new List<int> { 1, 2, 3 }
new List<int> { 1, 2, 3 }, new List<int> { 1, 5, 6 }
new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 3 }

 


判斷序列的"任何項目"是否"都"符合(頭獎)

解題方法: 我的號碼s.All  都符合 本期開獎號碼s.Any Equal

[TestMethod]
public void TestIsAllIn()
{
    Console.WriteLine($"測試結果: {IsAllin(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAllin(new List<int> { 1, 2, 3 }, new List<int> { 1, 2, 3 })}");
    Console.WriteLine($"測試結果: {IsAllin(new List<int> { 1, 2, 3 }, new List<int> { 1, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAllin(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 3 })}");
}

private bool IsAllin(List<int> MyLotteryNos, List<int> LotteryNos)
{
    return MyLotteryNos.All(p => LotteryNos.Any(q => q.Equals(p)));
}

 

測試結果,如預期的只有第二組符合All In

 


判斷序列的"任何項目"是否都不符合(雙贏彩)

解題方法: 我的號碼s.All  都符合 本期開獎號碼s.ALL Not Equal

[TestMethod]
public void TestIsAllNot()
{
    Console.WriteLine($"測試結果: {IsAllNot(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAllNot(new List<int> { 1, 2, 3 }, new List<int> { 1, 2, 3 })}");
    Console.WriteLine($"測試結果: {IsAllNot(new List<int> { 1, 2, 3 }, new List<int> { 1, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAllNot(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 3 })}");
}

private bool IsAllNot(List<int> MyLotteryNos, List<int> LotteryNos)
{
    return MyLotteryNos.All(p => LotteryNos.All(q => !q.Equals(p)));
}

 

測試結果,如預期的只有第一組符合All Not In

 


判斷序列的任一項目是否符合(安慰獎)

解題方法: 我的號碼s.Any  符合 本期開獎號碼s.Any Equal

[TestMethod]
public void TestIsAnyIn()
{
    Console.WriteLine($"測試結果: {IsAnyIn(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAnyIn(new List<int> { 1, 2, 3 }, new List<int> { 1, 2, 3 })}");
    Console.WriteLine($"測試結果: {IsAnyIn(new List<int> { 1, 2, 3 }, new List<int> { 1, 5, 6 })}");
    Console.WriteLine($"測試結果: {IsAnyIn(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 3 })}");
}

private bool IsAnyIn(List<int> MyLotteryNos, List<int> LotteryNos)
{
    return MyLotteryNos.Any(p => LotteryNos.Any(q => q.Equals(p)));
}

 

如預期的只有第一組為false,其他三組都有符合任一號碼。

 


小結

  • LINQ無敵。
  • 雙贏彩玩法: 雙贏彩是一種樂透型遊戲,您必須從01~24的號碼中任選12個號碼進行投注。開獎時,開獎單位將隨機開出12個號碼,這一組號碼就是該期雙贏彩的中獎號碼,也稱為「獎號」。您的12個選號如果全部對中當期開出之12個號碼,或者全部未對中,均為中頭獎
  • 今年夏天的俄羅斯世界盃,一場都沒買,希望把自己的好運留給家人。

 

2017.10 紐約中央公園的晨跑

 


參考

微軟Docs Enumerable.All<TSource> 方法 (IEnumerable<TSource>, Func<TSource, Boolean>)

微軟Docs Enumerable.Any 方法