简体   繁体   English

计数相同的数字,如果出现不止一次,则仅发生一次

[英]count the same number , if appears more than once, as one occurence only

So i am new to c sharp and been playing around with my code but could not figure it out. 因此,我对c Sharp还是陌生的,并且一直在使用我的代码,但无法弄清楚。 Let say i have the following: 假设我有以下内容:

Code : 2 1 1 1 1 2
Guess: 2 2 1 2 2 1

Firstly, ignore the spots where the guess matches the code. 首先,忽略猜测与代码匹配的地方。 After that, only 在那之后,只有

2 2 2 1 2 2 2 1

will be left for the guess and 将留给猜测和

1 1 1 2 1 1 1 2

for the code 为代码

If you see for the rest of the code, there is three 2's for the guess but only one in the code. 如果您在其余的代码中看到,则有3个2用于猜测,但在代码中只有1个。 I want to count the three 2's as only one occurrence but the part of my code accounts for all 3 which i cant seem to get it working to count as one. 我想将三个2算作一次,但是我的代码部分占了所有3个,我似乎无法将其算作一个。

Here is my code. 这是我的代码。 I only post the part im having trouble on. 我只发布即时通讯出现问题的部分。

if (guess.Contains(Code[i]))
{
       if (guess.Distinct().Count() > 1)
       diffSpot++;
}

I tried using distinct to get only unique numbers only and count to see that if its greater than 1 , it means there is dupe (same occurence in a row) but i guess im missing something. 我尝试使用distinct仅获得唯一数字,并计数以查看如果其大于1,则表示存在重复(连续出现相同的情况),但我想我错过了一些东西。 Thanks for any helpful hints and suggestions. 感谢您提供任何有用的提示和建议。

Liang, 梁,

Assuming that what you're after is this: 假设您所追求的是:

在此处输入图片说明

I kind of like LINQ for this: 我有点喜欢LINQ:

using System.Linq;
int[] Code = {2, 1, 1, 1, 1, 2};
int[] Guess = {2, 2, 1, 2, 2, 1};
int total =
     Guess.Select((g, i) => new {g, i})
    .Where(x => x.g != Code[x.i])
    .Select(x => x.g).Distinct().Count();

Returns 2. Hope this helps. 返回2。希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM