Shirt - Matching Pairs
A shop to increase sales during a festival has an offer that a customer will get a discount if the customer buys shirts having same size in pairs. Any customer who buys will choose N shirts and the size of the shirt is denoted by S(i) where 1 <= i <=N. Two shirts S(i) and S(j) are matching and form a pair only if S(i) = S(j).
The program must print the number of pairs eligible for the discount.
Input Format:
The first line will contain the value of N
The second line will contain the the size of N shirts S(1) to S(N) with each size separated by a space.
The first line will contain the value of N
The second line will contain the the size of N shirts S(1) to S(N) with each size separated by a space.
Output Format:
The first line will contain the number of matching pairs eligible for the discount.
The first line will contain the number of matching pairs eligible for the discount.
Constraints:
2 <= N <= 100
2 <= N <= 100
Example Input/Output 1:
Input:
9
10 20 20 10 10 30 44 10 20
Input:
9
10 20 20 10 10 30 44 10 20
Output:
3
3
Explanation:
The matching pairs are (10,10) (20,20) (10,10).
The matching pairs are (10,10) (20,20) (10,10).
Example Input/Output 2:
Input:
6
42 44 40 42 44 42
Output:
2
2
Explanation:
The matching pairs are (42,42) (44,44)
Code:The matching pairs are (42,42) (44,44)
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
List<Integer> li=new
ArrayList<Integer>();
Set<Integer> set=new
HashSet<Integer>();
int i,n=sc.nextInt();
int arr[]=new int[n];
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
li.add(arr[i]);
set.add(arr[i]);
}
int freq,count=0;
for(int no:set)
{
freq=Collections.frequency(li,no);
if(freq%2==1)
--freq;
if(freq%2==0)
{
freq/=2;
count+=freq;
}
}
System.out.print(count);
}
}
Please do comment If u have any Queries!
/*Alternate code*/
ReplyDeleteimport java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMaphm=new HashMap();
int count=0;
//int arr[]=new int[n];
for(int i=0;imap:hm.entrySet()){
if(map.getValue()%2==0 || map.getValue()>=2){
//System.out.println();
count=count+map.getValue()/2;
}
}
System.out.println(count);
}
}