Thursday, 26 November 2015

Kata Day 2: Printer Error


Problem Description:  In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from a to z.

Example:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"

Level: 7kyu

Link to Kata: Printer Error

To solve this Kata, I used a base array with characters from 'a-m' which I formed by using a split method.  Then I looped through the given color code string and compared the index of each character with the base array. I used a variable count which I incremented every time I  found the result of index comparison using array.indexOf() method equal to "-1".

To find the error fraction I kept the count in the numerator and length of input color code string in the denominator.

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 2 Kata

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

Happy coding. :)   

No comments:

Post a Comment