A task from codingame.com
Task
Binary with 0 and 1 is good, but binary with only 0, or almost, is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages.
Write a program that takes an incoming message as input and displays as output the message encoded using Chuck Norris’ method.
Here is the encoding principle:
- The input message consists of ASCII characters (7-bit)
- The encoded output message consists of blocks of 0
- A block is separated from another block by a space
- Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):
— First block: it is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
— Second block: the number of 0 in this block is the number of bits in the series
Input
Line 1: the message consisting of N ASCII characters (without carriage return)
Output
The encoded message
Tests
Input
|
Output |
C | 0 0 00 0000 0 00 |
CC | 0 0 00 0000 0 000 00 0000 0 00 |
% | 00 0 0 0 00 00 0 0 00 0 0 0 |
Hello | 0 0 00 00 0 0 00 000 0 00 00 00 0 0 00 0 0 000 00 0 0 00 00 00 0 00 00 0 0 00 00 00 0 00 00 0 0 0000 |
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
#include <iostream> #include <string> using namespace std; string binary(unsigned char x){ unsigned char mask=64; string s; for(int i=0; i<7; i++) { s.push_back((x&mask)>0 ? '1':'0'); mask=mask>>1; } return s; } int main() { string l; string a; unsigned char x; while(cin >> x){ l+=binary(x); } for(int i=0;i<l.size();i++) { if(l.at(i)=='0') { if(i==0||l.at(i-1)=='1') { if(i!=0) { a+=" "; a.push_back('0'); a.push_back('0'); a+=" "; } else { a.push_back('0'); a.push_back('0'); a+=" "; } } a.push_back(l.at(i)); } else if(l.at(i)=='1') { if(i==0||l.at(i-1)=='0') { if(i!=0) { a+=" "; a.push_back('0'); a+=" "; } else{ a.push_back('0'); a+=" "; } } a.push_back(l.at(i)); } } for(int i=0;i<a.size();i++) { if(a.at(i)=='1') { a.at(i)='0'; } } cout<<a; return 0; } |
Solution
First, we create a so called mask, which takes the symbol, transform it to a binary 7-bit number and return string. Then we add this string to another one, while transforming every symbol in the cin. Then we create a loop, where we check either symbol is 0 or 1 and add them to another string in the right order according to the encoding principle. In order to escape mistakes with ‘1’ in the first loop, we create another loop, where we change all ‘1’ to ‘0’.