Problem Description: Check to see if a string has the same amount of 'x's and 'o's. The method must return a Boolean and be case insensitive. The string can contain any char.
Examples input/output:
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
Level: 7kyu
Link to Kata: Exes and Ohs
The very first thing which came to my mind while attempting this Kata was to convert the whole input string to lower case. I did that by using toLowerCase() function of Javascript.
From there on it was easy to solve the Kata. I initialized two variables as a counter for 'o' and 'x' to zero. I used a while loop to go through the string and check the number of 'o' and 'x' and increment the counter accordingly.
At last I compared both the counters and if they were having the same value then the function returned true otherwise it returned false. There can be a case where there can be no 'o' or 'x' present in the string. The initialization of counter to a value of zero would help in such a case as it will return true.
Please keep in mind that this Kata can also be done with help of Regex and that would be a much efficient way to solve the problem. I am still learning Regex and I would be implementing them in future.
Here is a link to the code: Day 3 Kata
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment