Może komuś się przyda, napisałem sobie w celu samokształcenia na szybko.
Wiem, że od groma porównać można by było oszczędzić, ale jakoś nie chciało mi się komplikować.
http://wklej.org/id/635407/
#include <iostream>
#include <string>
#include <vector>
/*
Nihilist Cipher
C++ naive,not optimal implementation
Based on
http://www.cryptography.ovh.org/index.php?page=nihilisci
and
http://en.wikipedia.org/wiki/Nihilist_cipher
By Jadeszek
*/
const int WIDTH=5;
const int HEIGHT=5;
using namespace std;
bool is_in_array(char c, char tab[HEIGHT][WIDTH] )
{
for(int i=0; i<HEIGHT; i++)
{
for( int j=0; j<WIDTH ; j++ )
{
if(tab[i][j]==c) return false;
}
}
return true;
}
string transform_string(string text)
{
string result;
for(int i=0; i<text.size();i++)
{
size_t found=result.find(text[i]);
if(found==string::npos)
result.push_back(text[i]);
}
return result;
}
void write_to_array(string text, char tab[HEIGHT][WIDTH])
{
text=transform_string(text);
unsigned int counter=0;
unsigned int length=text.size();
char letter='A';
for(int i=0; i<HEIGHT; i++)
{
for( int j=0; j<WIDTH; j++)
{
if(counter<text.size())
{
tab[i][j]=text[counter];
counter++;
}
else
{
while(!is_in_array(letter, tab))
{
if(letter=='I')letter++;
letter++;
}
tab[i][j]=letter;
}
}
}
}
void print_array(char tab[HEIGHT][WIDTH])
{
for(int i=0; i<HEIGHT; i++)
{
for( int j=0; j<WIDTH ; j++ )
{
cout << tab[i][j];
}
cout << endl;
}
cout << endl;
}
vector<int> encode(string text,char tab[HEIGHT][WIDTH])
{
vector<int> encoded;
int counter=0;
while(counter<text.size())
{
for(int i=0; i<HEIGHT; i++)
{
for( int j=0; j<WIDTH ; j++ )
{
if(text[counter]==tab[i][j])
encoded.push_back( ((i+1)*10)+(j+1));
}
}
counter++;
}
return encoded;
}
void print_vect(vector<int> v)
{ for(unsigned int i=0;i<v.size();i++)
cout << v[i] << " ";
cout << endl;
}
vector<int> addition(vector<int> message, vector<int> key)
{
vector<int> result;
int t;
int i=0;
while(key.size()<message.size())
{
key.push_back(key[i]);
i++;
}
for(unsigned int j=0;j<message.size();j++)
{
t=message[j]+key[j];
result.push_back(t);
}
return result;
}
int main()
{
char key_array[HEIGHT][WIDTH] = {
{'_','_','_','_','_'},
{'_','_','_','_','_'},
{'_','_','_','_','_'},
{'_','_','_','_','_'},
{'_','_','_','_','_'}
};
string message="DYNAMITE WINTER PALACE";
string key1="ZEBRAS";
string key2="RUSSIAN";
vector<int> encoded_key1;
vector<int> encoded_message;
vector<int> cryptogram;
write_to_array(key1, key_array);
encoded_key1=encode(key2, key_array);
encoded_message=encode(message, key_array);
print_array(key_array);
cout<< "PT: "; print_vect(encoded_message);
cout<< "KEY:"; print_vect(encoded_key1);
cryptogram=addition(encoded_message, encoded_key1);
cout<< "CT: ";print_vect(cryptogram);
return 0;
}
To nie ma być ładne, to ma działać ;-P I te zadanie wydaje się spełniać.