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 :
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
Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →