加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 查找数组中没有对的数字

发布时间:2020-12-15 23:40:28 所属栏目:百科 来源:网络整理
导读:我遇到了一小段代码的问题,这些代码在随机大小的数组中,随机数对,除了没有对的代码. 我需要找到没有配对的号码. arLength是数组的长度. 但我实际上匹配对,并找到没有对的那个.. for (int i = 0; i = arLength; i++) { // go through the array one by one..
我遇到了一小段代码的问题,这些代码在随机大小的数组中,随机数对,除了没有对的代码.

我需要找到没有配对的号码.

arLength是数组的长度.
但我实际上匹配对,并找到没有对的那个..

for (int i = 0; i <= arLength; i++)
        { // go through the array one by one..
            var number = nArray[i];

            // now search through the array for a match.
            for (int e = 0; e <= arLength; e++)
            {
                if (e != i)
                {

                }
            }
        }

我也试过这个:

var findValue = nArray.Distinct();

我一直在寻找,但到目前为止,我还没有找到一种方法.

这段代码是生成数组的代码,但这个问题与代码的这一部分无关,只是为了清楚起见.

Random num = new Random();
            int check = CheckIfOdd(num.Next(1,1000000));
            int counter = 1;

            while (check <= 0)
            {
                if (check % 2 == 0)
                {
                    check = CheckIfOdd(num.Next(1,1000000)); ;
                }
                counter++;
            }
            int[] nArray = new int[check];
            int arLength = 0;
            //generate arrays with pairs of numbers,and one number which does not pair.
            for (int i = 0; i < check; i++)
            {
                arLength = nArray.Length;

                if (arLength == i + 1) 
                {
                    nArray[i] = i + 1;
                }
                else
                {
                    nArray[i] = i;
                    nArray[i + 1] = i;
                }
                i++;
            }

解决方法

Distict将为您提供具有不同值的数组.它找不到你需要的价值.

您可以使用GroupBy并选择Count modulo 2等于1的值.

var noPairs = nArray.GroupBy(i => i)
                    .Where(g => g.Count() % 2 == 1)
                    .Select(g=> g.Key);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读