Im having difficulty finding an algorithm for the following puzzle- A string is called ugly if it has 3 vowels in a row, or 5 consonants in a row, or both. A string is called nice if it is not ugly. You are given a string s, consisting of uppercase letters ('A'-'Z') and question marks ('?'). Can you find an algorithm that tells if the string can be made nice by substituting the question marks with alphabets?
Example -
"EE?FFFF" - Cant be made nice. Inserting either a consonant or a vowel would make it ugly.
"H??LOWOR??" - Can be made nice.
P.S - Not homework, but a part of a programming puzzle on the internet.
Note that the only strings that might potentially be ugly are those that are already ugly by virtue of the given letters or those which contain only singleton question marks. Here's the sketch of the proof:
So, we're left with two simple cases.
A solution in Haskell:
import System (getArgs)
nicePart :: Int -> Int -> String -> Bool
nicePart 3 _ _ = False
nicePart _ 5 _ = False
nicePart _ _ "" = True
nicePart v c ('?':as) = nicePart (v+1) 0 as || nicePart 0 (c+1) as
nicePart v c (a:as)
| a `elem` "AEIOU" = nicePart (v+1) 0 as
| otherwise = nicePart 0 (c+1) as
nice :: String -> Bool
nice as = nicePart 0 0 as
main = getArgs >>= print . nice . unwords
The function keeps a count of how many consecutive vowels and consonants have been seen up to the current point. If there are too many it returns False
. If a question mark is found, two recursive calls are made, one counting the question mark as a vowel, one as a consonant, checking if any of these variations is nice.
Here's the key: the transformability from ugly to nice is predicated upon a certain length of either consonants or vowels. So if transforming one block to nice would necessarily predicate the ugliness of another block, it cannot be done.
The implementation is left as an exercise for the person too lazy to do their own homework. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With