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

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →