Problem Description: Punky loves wearing different colored socks, but Henry can't stand it.
Given an array of different colored socks, return a pair depending on who was picking them out.
Example:
getSocks('Punky',['red','blue','blue','green']) -> ['red', 'blue']
Note that punky can have any two colored socks, in any order, as long as they are different and both exist. Henry always picks a matching pair.
If there is no possible combination of socks, return an empty array.
Level:7kyu
Link to Kata: 80's Kids #3: Punky Brewster's Socks
Another Kata from the 80's kids series. In this kata the aim was to return a pair of socks based upon who was choosing the socks and if such a pair was not possible then return an empty string.
In the starting I sorted the given array of socks so that if Henry tries to choose the socks then the repeated socks come in a sequence. I declare an answer array and a variable c which I have initialized to 0. Then I check if Henry or Punky were choosing the socks. Based on the name I loop through the sock array. If Punky is making the call then I choose two socks which are different in color. Push both socks in answer array and change the value of c to 1. If Henry is making the call then I check for two socks which are same in color. If I found such a pair then I push the pair to answer array and change the value of c to 1. In both cases if I get the desired result I break out of the loop.
In the end I check for the value of c. If it is equal to 1 then I return the answer array as a solution to this Kata else if its equal to 0 I return an empty array.
Here is a link to the code: Kata Day 34
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment