Cipher


Problem Statement :


Jack and Daniel are friends. They want to encrypt their conversations 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. Then it is written down  times, shifted by  bits. Each of the columns is XORed together to get the final encoded string.

If  and  it looks like so:

1001011     shift 0 
01001011    shift 1
001001011   shift 2
0001001011  shift 3
----------
1110101001  <- XORed/encoded string s
Now we have to decode the message. We know that . The first digit in  so our output string is going to start with . The next two digits are also , so they must have been XORed with . We know the first digit of our  shifted string is a  as well. Since the  digit of  is , we XOR that with our  and now know there is a  in the  position of the original string. Continue with that logic until the end.

Then the encoded message  and the key  are sent to Daniel.

Jack is using this encoding algorithm and asks Daniel to implement a decoding algorithm. Can you help Daniel implement this?

Function Description

Complete the cipher function in the editor below. It should return the decoded string.

cipher has the following parameter(s):

k: an integer that represents the number of times the string is shifted
s: an encoded string of binary digits
Input Format

The first line contains two integers  and , the length of the original decoded string and the number of shifts.
The second line contains the encoded string  consisting of  ones and zeros.


Output Format

Return the decoded message of length , consisting of ones and zeros.



Solution :



title-img


                            Solution in C :

In  C :






#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

   int n, k, i, j, pre, cur, a[1000000];
	char input[2000000];

	scanf("%d", &n);
	scanf("%d", &k);
	scanf("%s", input);

	if (input[0] == '1')
		pre = 1;
	else
	  	pre = 0;

	printf("%d", pre);
	a[0] = pre;
	for (i = 1; i < n; i++) {
		if (input[i] == '1') {
			printf("%d", (pre ^ 1) & 1);
			a[i] = (pre ^ 1) & 1;
		} else {
			printf("%d", (pre ^ 0) & 1);
			a[i] = (pre ^ 0) & 1;
		}
		pre = pre ^ a[i];
		if ((i - k + 2) > 0)
			pre = pre ^ a[i - k + 1];
	}
	printf("\n");    
    return 0;
}
                        


                        Solution in C++ :

In  C++  :






#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int N,K;
    cin>>N>>K;
    char a[N+K-1];
    cin>>a;
    int arr[N],sum=0,i;
    arr[0]=a[0]-48;
    sum=arr[0];
    for(i=1;i<N;i++){
        if(i>=K)sum=(sum-arr[i-K]);   
        if(a[i]=='0') arr[i]=sum%2;
        else arr[i]=(sum+1)%2;
        sum=sum+arr[i];
    }
    
//    arr[N-1]=a[N+K-2]-48;
    for(i=0;i<N;i++)
        cout<<arr[i];
    
    return 0;
}
                    


                        Solution in Java :

In  Java :








import java.io.*;

public class Solution {

    public static void solve(Input in, PrintWriter out) throws IOException {
        int n = in.nextInt();
        int k = in.nextInt();
        char[] c = in.next().toCharArray();
        int x = 0;
        char[] ans = new char[n];
        for (int i = 0; i < n; ++i) {
            ans[i] = (char) (((c[i] - '0') ^ x) + '0');
            x ^= ans[i] - '0';
            if (i >= k - 1) {
                x ^= ans[i - k + 1] - '0';
            }
        }
        out.println(ans);
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :








n, k = map(int, input().split())
s = input()
ans = []
pref = 0
for i in range(n):
    val = pref ^ (ord(s[i]) - ord('0'))
    ans.append(val)
    pref ^= val
    if i >= k - 1:
        pref ^= ans[i - k + 1]
print(''.join(map(str, ans)))
                    


View More Similar Problems

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →