Hackerrank - Cipher

Jack and Daniel are friends.They want to encrypt their conversation so that they can save themselves from interception by a detective agency. So they invent a new cipher.
Every message is encoded to its binary representation B of length N.
Then it is written down K times, shifted by 0,1….,K-1 bits.
If B=1001010 and K=4 it looks so :

Input
1001010
  1001010
    1001010
      1001010

Then calculate XOR in every column and write it down. This number is called S. For example, XOR-ing the numbers in the above example results in

Output
1110100110

Input Format
The first line contains two integers N and K.
The second line contains string S of length N+K-1 consisting of ones and zeros.

Output Format
Decoded message of length N, consisting of ones and zeros.

Sample Input
7 4
1110100110
Output
1001010
Explanation
1001010
  1001010
    1001010
      1001010
-------------------
1110100110


Solution
#!/bin/python
l, r = map(int, raw_input().split(" "))
msg = [int(i) for i in str(raw_input())]
ans = []
prev = 0
for i in range(l):
    msg[i] = msg[i] ^ prev
    ans.append(msg[i])
    prev = msg[i] ^ prev
    if i>=r-1:
        prev = prev ^ msg[i-r+1]

print "".join(map(str, ans))    

Comments

Best Programming language for machine learning.

Popular posts from this blog

Hackerrank - Dynamic Programming - The Coin Change Problem

Hackerrank - Implementation - Picking Numbers