Skip to content

Instantly share code, notes, and snippets.

@Vishal1297
Last active October 18, 2020 05:40
Show Gist options
  • Save Vishal1297/313c27346dc9e679a882b7e82f532bf9 to your computer and use it in GitHub Desktop.
Save Vishal1297/313c27346dc9e679a882b7e82f532bf9 to your computer and use it in GitHub Desktop.
2 Solutions : Using JavaScript And Java
// Save File As 'UniquePairs.js'
// To Run : node UniquePairs Or node UniquePairs.js
// Count Pairs
function sortAndCount(n, arr) {
// Sort Array
let sorted = arr.sort( (a,b) => a - b);
let pairs = 0;
for (let i = 0; i < n - 1; i = i + 2) {
if ( sorted[i] === sorted[i + 1]) {
pairs++;
}
}
return pairs;
}
// Input
n = 17
arr = [10, 10, 10, 10, 20, 30, 30, 30, 30, 30, 30, 30, 40, 40, 40, 40, 40];
// Output Total Pairs
console.log(sortAndCount(n, arr))
// Save File As 'UniquePairs.java'
// To Compile And Run : javac UniquePairs.java && java UniquePairs
import java.util.*;
public class UniquePairs {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
HashMap<Integer, Integer> counter = new HashMap<>();
// Input
for (int i = 0; i < N; i++) {
int sock = scanner.nextInt();
if (counter.containsKey(sock)) {
counter.put(sock, counter.get(sock) + 1);
} else {
counter.put(sock, 1);
}
}
int totalPairs = 0;
// Sum Total Pairs
for (int key : counter.keySet()) {
totalPairs += Math.floor(counter.get(key) / 2);
}
// Output Total Pairs
System.out.println(totalPairs);
scanner.close();
}
}
@Vishal1297
Copy link
Author

Vishal1297 commented Oct 18, 2020

PROBLEM :

Rohit works at a clothing store.

He has a large pile of socks that he must pair by colour 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 = 17 with color

arr = [1,1,1,1,2,3,3,3,3,3,3,3,4,4,4,4,4]

There is two pair of color 1 ,three of color 3 and two of color 4 . 

There are three odd socks left, one of color 2 , color 3 and color 4 . 

The number of pair is 7 .

SOLUTION :

  • JavaScript

  • Java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment