check repeated number inside the array c#

Asked

Viewed 6,243 times

3

I created a predefined array with some numbers, and I want to know how many repeated numbers there are in the array. but it is only returning the size of the array and not Qtd of repeated numbers. and also wanted to remove the repeated numbers.

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
int contador=0;

for(int i = 0; i < array1.Length; i++)
{
    for(int j = 0; j < array1.Length; j++)
    {
        if (array1[j] == array1[i])
        {
            contador++;
            break;

        }
    }
}

Console.WriteLine("Total de numeros repetidos -> " + contador);
  • Set "how many repeated numbers", this can be interpreted in various ways.

6 answers

5


Assign your array within a Hashset, as it does not accept repeated values, and then you compare the sizes of both and will know how many values were repeated:

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var meuHashSet = new HashSet<int>(array1);
var valoresRepetidos = array1.Length - meuHashSet.Count;
  • if I understood myHashSet gets my array already by removing the repeated numbers, then it has a new size? and valuesRepetidos gets myHashSet with new size, less the size my array1 .

  • The . Lenth and the . Count will count how many elements your collection has, so subtracting the size of the Hash with the normal array will tell you how many values were repeated.

  • Yes, myHashSet will already "remove" the repeated values directly.

  • 1

    Now I understood it was very clear and I didn’t even have to wear bows anymore

1

As commented,

Manieiro: Set "how many repeated numbers", this can be interpreted from various forms.

The proposed answer presents a solution that depends exactly on which question is being asked.

Gabriel Coletta

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var meuHashSet = new HashSet<int>(array1);
var valoresRepetidos = array1.Length - meuHashSet.Count;

The result presented is 5, result of original size difference Array subtracted from his Distinct, which may also be written as follows using the Linq

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
var quantidadeRepetidos = array1.Length - array1.Distinct().Count();

However, we have reached a subjective point, 5 actually represents the amount of repetitions of the values after their first occurrences, in other words, 5 is equal to duplicates or recurrences.

But when we look at the original set [2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8], we can see that it possesses 8 elements of repeated values (which have more than one occurrence). Which can be figured out more easily by reorganizing and removing unique occurrences [2,2,2,5,5,8,8,8]. And this difference impacts a lot on the purpose of the consultation and what you intend to do with this result.

But, the amount of repeated numbers can also aim, to know the amount of numbers that had more than one occurrence, in this case [2,5,8].

Below I leave an example script only to demonstrate how it could respond to interpretation variations according to the specified purpose, using some lists to facilitate manipulation and a single for().

int[] arrayOrignal = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };

var listUnicos = new List<int>();
var listRepetem = new List<int>();
var listDuplicatas = new List<int>();

int tamanho = arrayOrignal.Length;

for (int i = 0; i < tamanho; i++)
{
    var elemento = arrayOrignal[i];

    if (arrayOrignal.Where(x => x.Equals(elemento)).Count().Equals(1))
        listUnicos.Add(elemento);
    else if (!listRepetem.Contains(elemento))
        listRepetem.Add(elemento);
    else
        listDuplicatas.Add(elemento);
}

//[2, 5, 8, 10, 23, 4] -> 6 valores distintos
int[] arrayDistinto = arrayOrignal.Distinct().ToArray();

//[10, 23, 4] -> 3 valoes únicos
int[] arrayUnicos = listUnicos.ToArray();

//[2, 5, 8] ->  3 valores que repetem 
int[] arrayRepetem = listRepetem.ToArray();

//[2, 2, 5, 8, 8] -> 5 valores recorrentes
int[] arrayDuplicatas = listDuplicatas.ToArray();

//[2, 5, 8, 2, 2, 5, 8, 8] -> 8 valores repetidos
int[] arrayRepetidos = arrayOrignal.Where(x => listDuplicatas.Contains(x)).ToArray();
  • Very good remark on my reply, I am grateful for it, +1

  • @Gabrielcoletta, Cool that you liked and did not understand how a criticism to your answer, my goal was just to leave an observation related to the AP question.

0

You’re making two mistakes in your code:

The first is that the loop is checking the number itself, ie when i and j are equal it compares the same number. The second error is the break, when finding a repeated number should not interrupt the loop.

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
int contador=0;

for(int i = 0; i < array1.Length; i++)
{
    for(int j = i; j < array1.Length; j++)
    {
        if (i != j && array1[j] == array1[i])
            contador++;
    }
}

Console.WriteLine("Total de numeros repetidos -> " + contador);
  • Uhmm, your tested this but returns 14 repeated numbers, it doesn’t make sense

  • @Cezarmdlosci Yes sorry I forgot to consider that the second loop is sweeping all the elements so counting the numbers repeated more than once

0

You are always comparing two equal numbers so the counter at the end of the accounts has the same length value. If you don’t want to change the structure of your code, I suggest making these changes:

    int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };
    int contador=0;

    for(int i = 0; i < array1.Length; i++)
    {
        for(int j = i + 1; j < array1.Length; j++)
        {
            if (j != i && array1[j] == array1[i])
            {
                contador++;
                break;
            }
        }
    }

    Console.WriteLine("Total de numeros repetidos -> " + contador); //R:5 = 2, 2, 5, 8, 8

0

If you want to use can also extract both information:

Fetch items and do not bring repetitions:

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };

int[] arraySemRepeticao = array1.Distinct().ToArray();

Group items and count number of repetitions:

int[] array1 = { 2, 5, 8, 10, 2, 23, 2, 4, 5, 8, 8 };

var arrayAgrupadosRepeticaoCount = array1
             .GroupBy(x => x)
             .Select(a => new
               {
                  Item = a.Key,
                  Quant = a.Count()
               })
             .ToArray();

See working on dotnetfiddle.net

  • Pretty cool that ...!

-1

actually vc is comparing the repetition loop numbers and not the array int[] array1, you have to store the value of the array in a variable, and within the if you make the comparison between them and if they have the same value increment the accountant++

Browser other questions tagged

You are not signed in. Login or sign up in order to post.