Last active
October 18, 2020 05:40
-
-
Save Vishal1297/313c27346dc9e679a882b7e82f532bf9 to your computer and use it in GitHub Desktop.
2 Solutions : Using JavaScript And Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
SOLUTION :
JavaScript
Java