Friday, 25 December 2015

Kata Day 30: Character Counter


Problem Description: You are going to be given a word. Your job will be to make sure that each character in that word has the exact same number of occurrences. You will return true if it is valid, or false if it is not.

For example:

"abcabc" is a valid word because 'a' appears twice, 'b' appears twice, and'c' appears twice.
"abcabcd" is NOT a valid word because 'a' appears twice, 'b' appears twice, 'c' appears twice, but 'd' only appears 
once!
"123abc!" is a valid word because all of the characters only appear once in the word.

For this kata, capitals are considered the same as lowercase letters. Therefore: 'A' == 'a' .

Input

A string (no spaces) containing [a-z],[A-Z],[0-9] and common symbols. The length will be 0 < string < 100.

Output

true if the word is a valid word, or false if the word is not valid.

Level:7kyu

Link to Kata: Character Counter

Merry Christmas everyone!!

This turned out to be a lengthy Kata if we go through the brute force approach. If we use the regex then the solution can be simplified but I used the brute force approach to solve this. 

First I used few functions to convert the complete input string to lower case and then split each character of the string and stored them in an array. Then I sorted the array using .sort() function. I declared two empty arrays as "check" and "mid_ans". I looped through the array in which I have stored the characters of our input string and pushed the characters on each index to "mid_ans" array if the character on the looping index is same as the next character in the array. Otherwise I push the "mid_ans" array to "check" array and then reinitialized the "mid_ans" array to an empty array. 

Once I was done looping through the entire array  I initialized a variable c to a value of 1 and a target variable to the length of first element of "check" array. I looped through the entire check array from index 1 and checked if the length of every sub-array. If any of these lengths is not equal to the target variable I changed the value of c to 0 and break out of the loop. 

Based on the value of c I returned true or false as our answer for this Kata.

Here is a link to the code: Kata Day 30


Please mention your suggestions or your doubts in the comment below.


Happy coding. :)

No comments:

Post a Comment