每个int变量的值不同

本文关键字:int 变量 每个 | 更新日期: 2023-09-27 18:20:26

我有五个int变量:

int firstSequence;
int secondSequence;
int thirdSequence;
int fourthSequence;
int fifthSequence;

这些变量中的每一个都可以具有1-5之间的值。如果每个变量都有唯一的值,如何以最有效的方式进行检查?我的意思是只有一个可以具有值=1等

private bool IsOrderCorrect()
    {
        if(firstSequence != secondSequence && ...)
    }

每个int变量的值不同

只需将它们放入一个数组中,然后使用Distinct:

new [] { 
         firstSequence, 
         secondSequence, 
         thirdSequence,
         fourthSequence, 
         fifthSequence 
       }.Distinct().Count() == 5;

您可以尝试

(  (1 << firstSequence)
 | (1 << secondSequence)
 | (1 << thirdSequence)
 | (1 << fourthSequence)
 | (1 << fifthSequence))
== (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5);

开始

List<int> uniqueCheck = new List<int>() { firstSequence, secondSequence, thirdSequence, fourthSequence, fifthSequence };
if(uniqueCheck.Distinct().Count() == uniqueCheck.Count())
{
   //they are unique
}

我认为这不是最有效的方法。

最有效的方法是求和,并确保和等于15。

在我的机器上测试1000000次会导致.Dispinct().Count()==5方法耗时244.77毫秒。

做同样的事情,但使用.Sum()==15需要54.92,所以Sum方法更有效。

话虽如此,使用Distinct().Count()将推广到更多的情况,但操作需要最有效的方法。

编辑:

对不起,我打字的时候太匆忙了,所以有缺陷。我的一般方法保持不变,但你应该对平方求和,而不是对数字求和,我认为平方应该等于55,只有当数字不同时,平方才应该和到55。

使用平方和进行测试需要139毫秒,这仍然比.Dispinct().Count()==5 快

所以我的答案应该更新为。选择(x=>x*x).Sum()==55

如果它们在一个数组中,将非常容易

        int[] numbers = new int[] {1,2,3,4,5};
        for (int i = 0; i < numbers.Length; i++)
        {
            for (int j = 0; j!= i && j < numbers.Length; j++)
            {
                if (numbers[i] == numbers[j]) {
                    // you know what to do
                }
            }
        }