Program to decrypt code to defuse the bomb in Python



Suppose there is a bomb that you are going to defuse, and your time is running out! You have a a circular array code of length of n and have a key k. Now to decrypt the code, you must replace every number. All the numbers are replaced simultaneously. There are few rules −

  • If k > 0 then replace ith number with the sum of next k numbers.

  • If k < 0 then replace ith number with the sum of previous k numbers.

  • If k = 0 then replace ith number with 0.

Here the code is circular, so the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Finally we have to return the decrypted code.

So, if the input is like code = [8,2,3,5], k = 3, then the output will be [10, 16, 15, 13], because, for each key we replace with next three elements sum, so code[0] will be 10, code[1] will be 16, code[2] will be 15 and code[3] will be 13.

To solve this, we will follow these steps &mius;

  • decode := a new list

  • for i in range 0 to size of code - 1, do

    • if k > 0, then

      • sum := 0

      • j := i+1

      • m := k

      • while m is non-zero, do

        • sum := sum + code[j mod length of code]

        • m := m - 1

        • j := j + 1

      • insert sum at the end of decode

    • otherwise when k is same as 0, then

      • insert 0 at the end of decode

    • otherwise,

      • sum := 0

      • j := i-1

      • m := k

      • while m is non-zero, do

        • sum := sum + code[j mod length of code]

        • m := m + 1

        • j := j - 1

      • insert sum at the end of decode

  • return decode

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(code, k):
   decode = []
   for i in range(len(code)):
      if k > 0:
         sum = 0
         j = i+1
         m = k
         while(m):
            sum+=code[j%len(code)]
            m-=1
            j+=1
         decode.append(sum)

      elif k == 0:
         decode.append(0)

      else:
         sum = 0
         j = i-1
         m = k
         while(m):
            sum+=code[j%len(code)]
            m+=1
            j-=1
         decode.append(sum)

   return decode

code = [8,2,3,5]
k = 3
print(solve(code, k))

Input

[8,2,3,5], 3

Output

[10, 16, 15, 13]

Advertisements