Re:Ask HN: How do I solve problems/code outside of the book ...
by greenyoda on Saturday May 09, 2015 @05:35PM
(#9517777)
As another commenter (iovar) wrote, "try to solve this in your head with pseudo code do not overcomplicate it". There's actually nothing about this problem that requires splitting the input into words or storing the words in an array. You can just read one input character C at a time and either write CoC to the output (if a consonant) or copy C to the output (if any other character: vowel, white-space, punctuation, etc.). If a consonant character is capitalized, the one you write after the 'o' should be lower-cased. (Think of it as a Unix filter that copies a transformed version of its standard input stream to its standard output stream, like the Unix 'tr' command.)
Clickable link to original problem: https://www.reddit.com/r/dailyprogrammer/comments/341c03/201...
You need to break the problem into small steps. One step at the time. Then you unify the code. This is not a straight-forward process. For complex problems you might try to grab a problem from many different angles... That's why each user on Reddit gave a different solution. Not all solutions follow the same logic... But that's the good thing with programming, there are usually more than N solutions for each problem. Of course some are faster than others, some are better than others...
To give a practical example to the problem you're trying to solve:
1. Given a text, we need to separate the words. So we do need to 'split' a phrase into words.
2. It would be nice to have the words into an 'array'. Arrays are a very handy data structures for this kind of problem.
3. Now we need to iterate through the words and given a word, find the consonants. In order to do that, we need to split each word in to letters.
4. Then we need to iterate through each letter of the word, test if it's a consonant. How will you do that? I would create a list of consonants.. (Another Array! Too many Arrays you might think right?) and try to 'match' each letter with that 'array'.
4.1 Now if the 'letter' doesn't match with any item listed in 'consonants' array, do nothing. If it does match, substitute the consonant following the rules given from the problem.
6. Now we need to 'join' our letters together, with our substitutions.
7. Then we need to join the 'words' together adding spaces in between to re-form the phrase.
8. Then we need to print the final output.
That's a first version of this program which you can optimize later on... Until you end up with something that you like.
Later you might add exceptions and checks. Then you might find another way to make your program iterate through each letter/word faster using an algorithm (well python will do that for you probably, I wouldn't know as I am a ruby programmer but... I can guess it has already optimized functions for all these actions).
Good luck!