Search code examples
cpu-wordpuzzlecode-golfencryptionscramble

Code Golf - Word Scrambler


Please answer with the shortest possible source code for a program that converts an arbitrary plaintext to its corresponding ciphertext, following the sample input and output I have given below. Bonus points* for the least CPU time or the least amount of memory used.

Example 1:

Plaintext: The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!

Ciphertext: eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos

Example 2:

Plaintext: 123 1234 12345 123456 1234567 12345678 123456789

Ciphertext: 312 4213 53124 642135 7531246 86421357 975312468

Rules:

  1. Punctuation is defined to be included with the word it is closest to.
  2. The center of a word is defined to be ceiling((strlen(word)+1)/2).
  3. Whitespace is ignored (or collapsed).
  4. Odd words move to the right first. Even words move to the left first.

You can think of it as reading every other character backwards (starting from the end of the word), followed by the remaining characters forwards. Corporation => XoXpXrXtXoX => niaorCoprto.

Thank you to those who pointed out the inconsistency in my description. This has lead many of you down the wrong path, which I apologize for. Rule #4 should clear things up.

*Bonus points will only be awarded if Jeff Atwood decides to do so. Since I haven't checked with him, the chances are slim. Sorry.


Solution

  • Python, 50 characters

    For input in i:

    ' '.join(x[::-2]+x[len(x)%2::2]for x in i.split())
    

    Alternate version that handles its own IO:

    print ' '.join(x[::-2]+x[len(x)%2::2]for x in raw_input().split())
    

    A total of 66 characters if including whitespace. (Technically, the print could be omitted if running from a command line, since the evaluated value of the code is displayed as output by default.)


    Alternate version using reduce:

    ' '.join(reduce(lambda x,y:y+x[::-1],x) for x in i.split())
    

    59 characters.

    Original version (both even and odd go right first) for an input in i:

    ' '.join(x[::2][::-1]+x[1::2]for x in i.split())
    

    48 characters including whitespace.

    Another alternate version which (while slightly longer) is slightly more efficient:

    ' '.join(x[len(x)%2-2::-2]+x[1::2]for x in i.split())
    

    (53 characters)