I am trying to solve Sock Merchant problem from HackerRank .
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
n=7
socks with colorsar= [1,2,1,2,1,3,2]
. There is one pair of color1
and one of color2
. There are three odd socks left, one of each color. The number of pairs is2
.
My Code :
class Sock
{
public static void main(String args[])
{
int n=10;
int ar[] = new int[]{1,1,3,1,2,1,3,3,3,3};
int count = 0,number=0;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(ar[i]==ar[j])
{
count++;
}
}
if(count%2==0)
number++;
}
System.out.println("Pairs = "+number);
}
}
I am trying to do this problem with different approach .
like:
First ar[0]=1
frequency is 3 ,
count=3
include itself, then if count>1
and if count%2==0
then increment number++
,
so again if 1
come ar[2]=1
then again count 1's
frequency from ar[2]=1
.
then we got 1's
frequency 3,2,1
from ar[0]
to ar[6]
,ar[2]
to ar[6]
, ar[4]
to ar[6]
.
so we got 1's
pair 1 time
, '2's
pair 1 time
: total= 2 pairs
.