In this HackerEarth Roy and Cipher Disk problem solution, Roy's friends have been spying on his text messages, so Roy thought of an algorithm to encrypt text messages.

The Encryption algorithm is as follows:
  1. We say a message to be encrypted as Plain Text and an encrypted form of the message as Cipher.
  2. Plain Text consists of lower case alphabets only.
  3. Consider the Cipher Disk.

Initially, we start with 0 (zero). For each character in Plain Text, we move either clockwise or anti-clockwise on the disk depending on which way is closest to where we are currently standing.
If both clockwise and anti-clockwise distances are equal, we give priority to clockwise movement.
Clockwise movements are represented using positive numbers while Anti-clockwise movements are represented as negative numbers.

Roy needs your help in implementing this algorithm. Given a Plain Text message, your task is to encrypt it using the above algorithm and print the Cipher Text.


HackerEarth Roy and Cipher Disk problem solution


HackerEarth Roy and Cipher Disk problem solution.

def roy_and_cipher_disk():
    base = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1]
    pre = []
    for i in xrange(26):
        tmp = base[(26-i):] + base[:(26-i)]
        pre.append(tmp)
    for t in xrange(input()):
        s = raw_input()
        slen = len(s)
        res = []
        curr = 'a'
        for i in xrange(slen):
            res.append(str(pre[ord(curr)-ord('a')][ord(s[i])-ord('a')]))
            curr = s[i]
        print ' '.join(res)
roy_and_cipher_disk()


Second solution

t=input()
assert(t<=100 and t>=1)
while t:
    x=raw_input()
    cur=0
    n=len(x)
    assert(n<=100 and n>=1)
    for i in xrange(n):
        p=ord(x[i])-97
        assert(p<26)
        j=cur
        distc=dista=0
        while 1:
            if j==p: break
            distc += 1
            j = (j+1)%26
        j=cur
        while 1:
            if j==p: break
            dista += 1
            j = (j-1+26)%26
        if distc<=dista: print distc,
        else: print -1*dista,
        cur=p
    print 
    t-=1