Created
September 21, 2010 04:02
-
-
Save anisaraf/589166 to your computer and use it in GitHub Desktop.
Srm144BinaryCodeHerb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<vector> | |
#include<iostream> | |
using namespace std; | |
class BinaryCode { | |
private: | |
char decodeChar(const string& message, const string& decoded, int pos){ | |
if(pos == 1) return (getIntFromChar(message[pos-1]) - getIntFromChar(decoded[pos-1]) + '0'); | |
return (getIntFromChar(message[pos-1]) - getIntFromChar(decoded[pos-2]) - getIntFromChar(decoded[pos-1]) + '0'); | |
} | |
int getIntFromChar(const char c){ | |
return (c - '0'); | |
} | |
public: | |
vector<string> decode(const string& message){ | |
vector<string> rVector; | |
rVector.push_back("NONE"); | |
rVector.push_back("NONE"); | |
//special case | |
if(message.length() == 1){ | |
if(message[0] == '0') | |
rVector[0] = "0"; | |
else if(message[0] == '1') | |
rVector[1] = "1"; | |
return rVector; | |
} | |
// loop twice - once for p[0] = 0 and then for p[0] =1 | |
for(int i = 0; i < 2; i++) { | |
string rString = ""; | |
rString.push_back(i + '0'); | |
int j = 1; | |
for(; j < message.length(); j++){ | |
char cZero = decodeChar(message, rString, j); | |
if(cZero != '0' && cZero != '1') | |
break; | |
else | |
rString.push_back(cZero); | |
} | |
// sanity check | |
if(j == message.length()) | |
if(getIntFromChar(message[message.length()-1]) == getIntFromChar(rString[rString.length()-1]) + getIntFromChar(rString[rString.length()-2]) ) | |
rVector[i] = rString; | |
} | |
return rVector; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment