Tuesday, April 21, 2015

Another recursion post - Character Search!

This is related to another CodingBat recursion problem. Specifically, this one.

Basically, it recursively searches through a number to find a specific digit, which, in this case, is 7. It then counts how many times that digit is found in the number, if any (e.g. 127 would return 1).

I made this into a program that, instead of just searching through numbers for a given digit, can search through any sort of string for a given character (which, in the program, is technically just a string of length 1). While the task could be accomplished with a for loop, I decided to keep with the format of the CodingBat problem, only changing a few if statements to deal with strings as opposed to numbers.

The program can be found here.

Interestingly, it was easier to comprehend the recursive function of the program in terms of strings than it was with numbers. For example, getting the last digit in a number requires the modulo operator and the number 10. So, 126 % 10 = 6.  When doing the same thing with strings, all you need is a substring - specifically, a substring from str.length() - 1 to str.length()

Similarly, to get a number to change to all the digits but the final one, you have to divide by 10, and be sure to avoid floats/doubles: 126 / 10 = 12. With substrings, you just need to go from 0 to str.length() - 1

All of these transformations are needed in the recursive function. After reformatting it for strings and implementing a user input system, the program was pretty much complete. I had a little trouble getting multiple inputs to work (so the user can input the character to search for and the string to search in within the same window), but found some help online.

Here's the program in action:



------------------------------------------------------------------------------------------------



------------------------------------------------------------------------------------------------



------------------------------------------------------------------------------------------------



An interesting anecdote - while testing this program at my house, I tried to input a large document from Wikipedia into the righthand box. While it technically ran correctly, it ended up forcing my computer into Windows 7 Basic Desktop mode, as opposed to Aero Desktop, and didn't go back until I closed the program. So that's weird.

No comments:

Post a Comment