Home > Back-end >  Is there a way to searchfor duplicate entries in an array in c#
Is there a way to searchfor duplicate entries in an array in c#

Time:08-11

I'm trying to code a Yahtzee game in C# with the .NET Framework in C#, but couldn't find a way for check if a fullhouse, three of a kind or four of a kind was generated. For all other possibilities I save the numbers in an Array and check with an if statement if an 1 or 2 is in it.

This is my code:

string[] numbers = { number1, number2, number3, number4, number5 };

if (numbers.Contains(1)) {
    foreach (int i in numbers)
    {
        if (i == "1")
        {
            int num = num   1;
        }
    }
}

CodePudding user response:

If you need to count how many times a number repeats in your array you can use Linq GroupBy

The output of this code

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string[] numbers = new string[] { "1", "2", "1", "2", "1" };
        var groups = numbers.GroupBy(n => n);
        foreach (var g in groups) {
            Console.WriteLine($"Number: {g.Key} Count: {g.Count()}");
        }
    }
}

is

Number: 1 Count: 3
Number: 2 Count: 2

CodePudding user response:

You have an unnecessary check, 2 syntax errors, and a logical error (see comments in code):

string[] numbers = { "1", "1", "2", "3", "6" };

// Not needed because it will internally iterate the array, which you then
// do in your own code:
// if (numbers.Contains("1")) // Also, your code used an int rather than string

int numberOfOnes = 0;
foreach (var i in numbers) // Not type int
{
    if (i == "1")
    {
        // Don't declare inside the loop since you get a fresh variable each time:
        //int num = num   1;
        numberOfOnes  ;
    }
}

// Outputs 2 as expected:
Console.WriteLine($"Number of ones: {numberOfOnes}");

You can also accomplish this with a single line of Linq:

var numberOfOnes = numbers.Where(n => n == "1").Count();

CodePudding user response:

There are quite a few syntax errors in the code you posted but you could use a method along these lines:

public static bool IsYahtzee(string[] numbers)
{
  if(numbers.All(x => x == numbers[1]))
    return true;
        
  return false;
}

This obviously assumes all of these string values are valid numbers but it will return true if all the values in the array are equal to the first value in the array.

  • Related