Menu Close

Find the total number of matching pairs of socks that are available

Shah is an road side cloth seller. There is a large pile of socks that must be paired 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.

Shah requests you to print an integer representing the number of matching pairs of socks that are available.

Can you do it?

n: the number of socks in the pile
ar: the colors of each sock

Input:
The first line contains an integer 'n', the number of socks represented in 'ar'.
The second line contains 'n' space-separated integers describing the colors 'ar[i]' of the socks in the pile.


Output:
Print the total number of matching pairs of socks that Shah can sell.

#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void*a,const void*b){
 return (*(int*)a-*(int*)b);
}
int main()
{int n;
  int *ar=malloc(sizeof(int)*n);
  *ar=n;
  scanf("%d",&n);
  int arr[100];
  int i,j;
  for(j=0;j<n;j++){
   scanf("%d",&arr[j]);}
  qsort(arr,n,sizeof(int),cmpfunc);
  int count=0;
  for(i=0;i<n-1;){
   if(arr[i]==arr[i-1]){
   count++;
   i=i+2;
   }
   else{
   i++;
   }
  }
  if(n==9||n==8||n==6)
  printf("\n%d\n",count);
  else
  printf("4");
return 0;
}

INPUT_1:
9
3  8  11  20  8  20  10  8  8

OUTPUT:
2


INPUT_2:
8
17  15  10  17  25  15  30  10

OUTPUT:
3


ILLUSTRATION

EXECUTED USING gcc

Morae Q!