Skip to content

Instantly share code, notes, and snippets.

@adyngom
Last active October 20, 2022 07:00
Show Gist options
  • Save adyngom/30181d2f54cb4a2e36ba810292f4b17b to your computer and use it in GitHub Desktop.
Save adyngom/30181d2f54cb4a2e36ba810292f4b17b to your computer and use it in GitHub Desktop.
/**
* Couple of possible solutions to the Sock Merchant challenge on Hacker Rank
* https://www.hackerrank.com/challenges/sock-merchant/problem
**/
// Solution 1
// Video tutorial can be viewed: https://youtu.be/DRp6naqL5uc
function sortAndCount( n, arr ) {
let sorted = arr.sort( (a,b) => a - b);
let pairs = 0;
for (let i = 0; i < n - 1; i++) {
if ( sorted[i] === sorted[i + 1]) {
pairs++;
i += 1;
}
}
return pairs;
}
// Solution 2
// Video tutorial: will add URL soon
function stockAndCount( n, arr ) {
let pairs = 0;
const colors = arr.reduce((acc, val) => {
(!!acc[val]) ? acc[val] += 1 : acc[val] = 1;
return acc;
}, {});
Object.keys(colors).forEach( n => {
let _pair = parseInt( colors[n] / 2);
if ( _pair >= 1 ) pairs += _pair;
});
return pairs;
}
const n = 9;
const socks = [10, 20, 20, 10, 10, 30, 50, 10, 20];
console.clear();
console.group('Sorted and counted');
console.log(`There is a total of ${sortAndCount(n, socks)} pairs`);
console.groupEnd();
console.group('Stocked and counted');
console.log(`There is a total of ${stockAndCount(n, socks)} pairs`);
console.groupEnd();
@keandreMensah
Copy link

thanks bro

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