diam
diam

Reputation: 49

Finding duplicate values in an array and outputing all of them

So I have some working code for outputting duplicate values in an array, however it is always one short when it outputs them on the screen and I know it has to do with the following code, but I just can't put my finger on it. Please note I can't use any System.Array.

for (column = 0; column < WinningScores.Length -1 ; column++) 
{
    if (WinningScores[column] == WinningScores[column + 1]) 
    {
        duplicateScore = WinningScores[column];
        duplicateIndex = column;
        Console.Write("\n Competitor {0} is the Winner with a total of: {1}", 
                      duplicateIndex + 1, 
                      duplicateScore - totalSum);
    }
}

Upvotes: 2

Views: 113

Answers (3)

JP Hochbaum
JP Hochbaum

Reputation: 647

//Starts loop through first element
for(int i = 0; i < arr.length, i++)

//starts at second element in array
for(int j = i + 1; k < arr.length, j++)

//double check my logic though, in a hurry at work so had to post this in a rush.

Upvotes: 0

MNF
MNF

Reputation: 717

Your code looks for duplication in consécutive values. Try this code to output duplicate values in an array.

  for (column = 0; column < WinningScores.Length -1 ; column++) 
     {

        for (int cl= column + 1 ; cl < WinningScores.Length - 1 ; cl++)
            {
               if (WinningScores[column] == WinningScores[cl]) {


                        duplicateScore = WinningScores[column];
                        duplicateIndex = column;
                        Console.Write("\n Competitor {0} is the Winner with a total  of: {1}", duplicateIndex + 1, duplicateScore - totalSum);
              }
             }
         }

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117057

You could try using LINQ for this:

double[] WinningScores = new double[] { 4, 5, 3, 5 };

var duplicates =
    WinningScores
        .Select((score, index) => new { score, player = index + 1})
        .GroupBy(x => x.score, x => x.player)
        .Where(gxs => gxs.Count() > 1);

That gives me this result:

result

You can see that it picked up the duplicate score of 5 with players 2 & 4.

Upvotes: 3

Related Questions