CodeJam Quickie: 2010 Africa – Qualification C

Whoa! Keeping up with the Africa 2010 contest, enter the Qualification C problem: T9 Spelling! It was a very fun problem and says:

The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters. The letters are mapped onto the digits as shown below. To insert the character B for instance, the program would press 22. In order to insert two characters in sequence from the same key, the user must pause before pressing the key a second time. The space character ' ' should be printed to indicate a pause. For example, 2 2 indicates AA whereas 22 indicates B.

Reminds me of those days of texting through that old indestructible Nokias! Anyway, it’s not hard to do, but requires some data disposition. I chose to create a map to lists containing keys and the amount of keystrokes for every letter (including space, which would be 0), in order to simply match letters and print the sequence right along. Also, to know when to pause, I would check the last printed character before, so I can print a space and then the sequence.

Python code followsas usual:

# Build a map with the number to write and its repetition count
t9 = {
        "a" : ["2", 1], "b" : ["2", 2], "c": ["2", 3],
        "d" : ["3", 1], "e" : ["3", 2], "f": ["3", 3],
        "g" : ["4", 1], "h" : ["4", 2], "i": ["4", 3],
        "j" : ["5", 1], "k" : ["5", 2], "l": ["5", 3],
        "m" : ["6", 1], "n" : ["6", 2], "o": ["6", 3],
        "p" : ["7", 1], "q" : ["7", 2], "r": ["7", 3], "s": ["7", 4],
        "t" : ["8", 1], "u" : ["8", 2], "v": ["8", 3],
        "w" : ["9", 1], "x" : ["9", 2], "y": ["9", 3], "z": ["9", 4],
        " " : ["0", 1],
}

for case in range(1,int(raw_input())+1): # For all test cases
    message = raw_input()                # Get the list of words

    attr = t9[message[0]]                # Start with the first character
    t9str = attr[0]*attr[1]              # Initialize t9str with first T9 "word"

    for i in range(1,len(message)):      # From the second character on
        attr = t9[message[i]]            # Get the map values
        if t9str[-1] == attr[0]:         # If it's the same number as the last
            t9str += " "                 # Add a space

        t9str = t9str+attr[0]*attr[1]    # Append the new T9 "word"

    print "Case #%d: %s" % (case, t9str) # Reports results

It was the hardest of the Qualification problems, but still very easy to develop. 🙂 Fun! See ya tomorrow!

Advertisement

Comment this

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s