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();
Set "how many repeated numbers", this can be interpreted in various ways.
– Maniero