Javascript Sock Merchant Challenge - Solution 2
Ady Ngom
Posted on April 26, 2019
You can find Part 1 here
Javascript Sock Merchant Challenge - Solution 1
Ady Ngom ・ Apr 23 '19
The challenge
Hacker Rank Sock Merchant Page
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
The code
javascript
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;
}
Video Transcript
In part 1 we solved the challenge using a sort first and compare approach, let’s clean up and look at an alternative solution.
Using the stockAndCount function, we will create an object that will stock each of our colors as keys.
So we will still create a pairs variable, then we will have a colors variable here but using the reduce method here we will be building up this object as we go.
In the reduce callback we setup an accumulator and the current value - doing this on the fly we check to see if our current value exists as a key in our accumulator object, if so we add one to it if not we create the key and initialize it with 1.
Let’s not forget to add the empty object as the second argument and return the accumulator after each iteration
Let’s make sure the function is properly closed
What we have done above is what I call the Dictionary approach.
Now that we have an object with each color as a key ket’s loop through it.
We iterate through each key and we create a local pair variable. We initialize the pair by dividing the colors n key value by 2
Now we can check if the pair value is greater or at least equal to 1. If true we can increment the total pairs value on line 17 with the number of pairs found
We can then simply return the total count after the loop. Running it in the terminal gives us again 3 pairs - If that went too fast let’s add to our console statement and run it again
We first used a sort and count approach in the last episode and today we looked at the Dictionary approach to stock each color as key and total up the pair count.
In the next and final episode we will discuss why the second approach is a better approach. In the meantime please let me know what you think about each and why one might be better than the other in the comments.
Cheers
Posted on April 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.