John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
Question from hackerrank.
Solution in C# -
class Solution {
static int sockMerchant(int n, int[] ar) {
List<int> distinct = new List<int>();
for(int i=0; i<ar.Length; i++)
if(!distinct.Contains(ar[i]))
distinct.Add(ar[i]);
int pairs = 0;
for(int i=0; i<distinct.Count; i++)
{
int x = 0;
for(int j=0; j<n; j++)
{
if(distinct[i] == ar[j])
x++;
if(x==2)
{
pairs++;
x=0;
}
}
}
return pairs;
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp));
int result = sockMerchant(n, ar);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
Post a Comment