Tengo esta matriz llena de colores y tengo que encontrar el que solo aparece una vez en la matriz.
string[] colors = {"red","green","white","green","red","red"} string[] noDupcolors = szinek.Distinct().ToArray(); //the same array without duplicates int num = 0; int once = 0; for (int i = 0; i < noDupcolors.Length; i++) { for (int j = 0; j < S; j++) { if (noDupcolors[i]==colors[j]) { num++; } if (num == 1) { once = j; } else { nums = 0; } } } Console.WriteLine(colors[once]);He intentado esto, pero por alguna razón se escribe en verde. Puede alguien ayudar, por favor. Gracias.
Puedes usar LINQ
var result = colors.GroupBy(x => x) .Single(x => x.Count() == 1) .Key;Ejemplo en vivo: https://dotnetfiddle.net/lBmR7R
Tenga en cuenta que esto arrojará una excepción si hay cero o más de 1 color de ocurrencia única en la matriz, podría usar algo como First , FirstOrDefault o SingleOrDefault en lugar de Single
LINQ es la forma correcta de hacerlo aquí. Pero como este es probablemente un ejercicio de aprendizaje, aquí hay un método para calcular palabras de una sola ocurrencia usando un diccionario.
string[] colors = {"red","green","white","green","red","red"}; Dictionary<string,int> distinctColors = colors.Distinct().ToDictionary(x=> x, v => 0); foreach(var color in colors) { distinctColors[color] ++; } var singleOccurance = new List<string>(); foreach(var dc in distinctColors) { if(dc.Value == 1) { singleOccurance.Add(dc.Key); } } if(singleOccurance.Count() == 0) { Console.WriteLine("No single occurance colors found"); } else if(singleOccurance.Count() > 1) { Console.WriteLine("Multiple single occurance colors found"); } else { Console.WriteLine(singleOccurance[0]); }También hay una opción para usar Sort() para contar grupos:
string[] colors = { "red", "green", "white", "green", "red", "red" }; Array.Sort(colors); var unique = new List<string>(); for (int lo = 0, hi = 1; hi <= colors.Length; hi++) { if (hi == colors.Length || colors[hi] != colors[lo]) { if (hi - lo == 1) // count number of elements in a group. { unique.Add(colors[lo]); } lo = hi; } }