Sock Merchant Solution in C | Hacker Rank

In this Article I am writing the Code for Hacker Rank problem on Sock Merchant  in C programming Language . 

Q) 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 .


Solution:

As you are required to know how many pairs are present.
lets say if 1 is called a color "red" and 2 is called a color "green".
so number of pairs of 1 that is red in above array ar is 1 .
if you ask how?
remember pair is formed when there is 2 similar color.in the above array
there are 3 1's(red) therefore 1 Pair is formed .
if there was 4 1's(red) then you would get 2 pairs.


#include <stdio.h>
int main()
{
int a[100],n,i,temp,c=0;

scanf("%d",&n);
//printf("enter number in array");
for(i=0;i<n;i++)
{
    scanf("%d",&a[i]);
}
for(i=0;i<n;i++) // sort
{
  for(int j=i+1;j<n;j++) 
  {
      if(a[i]>a[j])
   {
       temp=a[i];
       a[i]=a[j];
       a[j]=temp;
   }
  }
}
//printf("SORTED number in array");
for(i=0;i<n;i++) // sort
{
  //  printf("%d\t",a[i]);
}

for(i=0;i<n;i++) 
{
    if(a[i]==a[i+1])
    {
        c++;
        i++;
    }
}
printf("%d",c);
}

Comments

Popular posts from this blog

Write a Function | Hacker Rank Solution in Python

Diagonal Difference | Hacker Rank Solution in C

Print Function | Hacker Rank Solution in Python