Last active
October 13, 2022 13:10
-
-
Save trafficinc/9a4787afbd59ee0d57557b1f59ea44f6 to your computer and use it in GitHub Desktop.
Leetcode - Sales by Match Algorithm
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
/* | |
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. | |
Example | |
n = 7 | |
ar = [1,2,1,2,3,1,2] | |
There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2. | |
Function Description | |
Complete the sockMerchant function in the editor below. | |
sockMerchant has the following parameter(s): | |
int n: the number of socks in the pile | |
int ar[n]: the colors of each sock | |
Returns | |
int: the number of pairs | |
Input Format | |
n, ar | |
Stdin #1: | |
10 | |
1 1 3 1 2 1 3 3 3 3 | |
Stdin #2: | |
9 | |
10 20 20 10 10 30 50 10 20 | |
*/ | |
// a possible solution | |
function sockMerchant(n, ar) { | |
let count = 0; | |
let hash = {}; | |
ar.forEach(x => { | |
hash[x] ? hash[x] += 1 : hash[x] = 1 | |
}) | |
let numsUnique = new Set(ar); | |
numsUnique.forEach(i => { | |
if (hash[i] >= 2){ | |
count += (hash[i] / 2) >> 0; | |
} | |
}) | |
return count; | |
} | |
sockMerchant(10, [1,1,3,1,2,1,3,3,3,3]); | |
sockMerchant(9, [10,20,20,10,10,30,50,10,20]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment