• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

100
Views
C# Finding the word that only appears once in an array

I have this array full of colors and have to find the one that only appears once in the array.

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]);

I've tried this but for some reason it writes out green. Can someone help please. Thank you.

4 months ago ·

Santiago Trujillo

3 answers
Answer question

0

You can use LINQ

var result = colors.GroupBy(x => x)
        .Single(x => x.Count() == 1)
        .Key;

Live example: https://dotnetfiddle.net/lBmR7R

Note that this will throw an exception if there are zero or more than 1 single-occurance color in the array, you could use something like First, FirstOrDefault or SingleOrDefaultin place of Single

4 months ago · Santiago Trujillo Report

0

LINQ is the correct way to go here. But as this is probably a learning exercise, here is a method of calculating single occurrence words using a dictionary.

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]);
}
4 months ago · Santiago Trujillo Report

0

There is also an option to use Sort() to count groups:

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;
     }
 }
4 months ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.