SPOJ: 400. To and Fro

Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of columns and write the message (letters only) down the columns, padding with extra random letters so as to make a rectangular array of letters. For example, if the message is “There’s no place like home on a snowy night” and there are five columns, Mo would write down

t o i o y
h p k n n
e l e a i
r a h s g
e c o n h
s e m o t
n l e w x

Note that Mo includes only letters and writes them all in lower case. In this example, Mo used the character ‘x’ to pad the message out to make a rectangle, although he could have used any letter. Mo then sends the message to Larry by writing the letters in each row, alternating left-to-right and right-to-left. So, the above would be encrypted as

toioynnkpheleaigshareconhtomesnlewx

Your job is to recover for Larry the original message (along with any extra padding letters) from the encrypted one.

Problem: Sphere Online Judge (SPOJ) – Problem TOANDFRO

Solution: Let’s do this on a small example. The message should be ABCDEFGHIJKL with three columns. Therefore we get:

A E I
B F J
C G K
D H L

If we merge these lines together, we get:

A E I   J F B   C G K   L H D

You can see that you need the first character from the first element, the third from the second, the first from the third, etc. To make this a bit easier I decided to reverse every second element.

A E I   B F J  C G K  D H L

Now we can just take all the firsts characters from every element, then the second characters and finally the thirds and we’re done.

while True:
    code = int(raw_input())
    if code == 0:
        break
     
    line = raw_input()

    segments = []
    j = 0

    for i in xrange(0, len(line), code):
        if j % 2 == 1:
            # reverse every odd segment
            tmp = list(line[i:i + code])
            tmp.reverse()
            segments.append("".join(tmp))
        else:
            segments.append(line[i:i+code])
                
        j += 1
        
    out = []
    for i in xrange(0, code):
        for f in segments:
            out.append(f[i])

    print "".join(out)