-
Notifications
You must be signed in to change notification settings - Fork 0
/
railfence.cpp
134 lines (112 loc) · 3.06 KB
/
railfence.cpp
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include<iostream>
#include<vector>
#include<stdbool.h>
using namespace std;
vector<vector<char>> railFence(string& plain, int key);
string encrypt(vector<vector<char>>& fence);
vector<vector<char>> railFenceInverse(string& plain, int key);
string decrypt(vector<vector<char>>& fence, string& cipher, int key);
void printMatrix(string& msg, int key);
int main(){
int key;
cin>>key;
string plain;
cin >> plain;
vector<vector<char>> fence = railFence(plain, key);
printMatrix(plain, key);
string cipher = encrypt(fence);
cout<<"\n Cipher: "<<cipher;
vector<vector<char>> fenceInverse = railFenceInverse(cipher, key);
plain = decrypt(fenceInverse, cipher, key);
// plain = squash(fenceInverse);
cout<<"\n Plain: "<<plain;
}
vector<vector<char>> railFence(string& plain, int key){
vector<vector<char>> fence(key);
int row = 0;
bool toIncrease = true;
for(auto ch: plain){
ch = toupper(ch);
if(row == 0) toIncrease = true;
else if(row == key - 1) toIncrease = false;
if (toIncrease) {
fence[row%key].push_back(ch);
row++;
}
else {
fence[row%key].push_back(ch);
row--;
}
}
return fence;
}
vector<vector<char>> railFenceInverse(string& cipher, int key){
// string test = "hhhhhh";
vector<vector<char>> fenceInverse = railFence(cipher, key);
int pos = 0;
// for(auto row: fenceInverse){
for(int i = 0; i<key; i++){
for(int j = 0; j<fenceInverse[i].size(); ++j){
fenceInverse[i][j] = cipher[pos++];
}
}
return fenceInverse;
}
string encrypt(vector<vector<char>>& fence){
string chapathi;
for(auto row: fence){
for(auto ch: row){
chapathi.push_back(ch);
}
}
return chapathi;
}
string decrypt(vector<vector<char>>& fence, string& cipher, int key){
int row = 0;
bool toIncrease = true;
string chapathi;
for(auto ch: cipher){
if(row == 0){
toIncrease = true;
}
else if(row == key - 1) {
toIncrease = false;
}
if (toIncrease) {
chapathi.push_back(fence[row%key][0]);
fence[row%key].erase(fence[row%key].begin());
++row;
}
else {
chapathi.push_back(fence[row%key][0]);
fence[row%key].erase(fence[row%key].begin());
--row;
}
}
return chapathi;
}
void printMatrix(string& msg, int key){
int spaces = key;
bool toIncrease = true;
cout<<endl;
for(auto ch: msg){
if(toIncrease){
for(int i=0; i<spaces; i++){
cout<<" ";
}
spaces--;
} else {
spaces++;
for(int i=1; i<spaces; i++){
cout<<" ";
}
}
if(spaces == key) {
toIncrease = true;
}
else if(spaces == 0){
toIncrease = false;
}
cout<<ch<<endl;
}
}