Last active
October 20, 2022 07:00
-
-
Save adyngom/30181d2f54cb4a2e36ba810292f4b17b to your computer and use it in GitHub Desktop.
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
/** | |
* 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks bro