forked from derekhh/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyword-transposition-cipher.cpp
More file actions
80 lines (74 loc) · 1.42 KB
/
keyword-transposition-cipher.cpp
File metadata and controls
80 lines (74 loc) · 1.42 KB
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
//keyword-transposition-cipher.cpp
//Keyword Transposition Cipher
//Algorithms - Discrete Mathematics
//Author: derekhh
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
char grid[20][20];
string str;
bool cmp(int a, int b)
{
return grid[0][a] < grid[0][b];
}
int mapping[26], reversemap[26];
int main()
{
int t;
cin >> t;
while (t--)
{
bool used[26];
memset(used, false, sizeof(used));
memset(grid, 0, sizeof(grid));
cin >> str;
int len = (int)str.size(), ncol = 0;
int order[10];
for (int i = 0; i < len; i++)
order[i] = i;
for (int i = 0; i < len; i++)
{
if (!used[str[i] - 'A'])
{
used[str[i] - 'A'] = true;
grid[0][ncol++] = str[i];
}
}
sort(order, order + ncol, cmp);
int nrow = 1, col = 0;
for (int i = 0; i < 26; i++)
{
if (!used[i])
{
used[i] = true;
grid[nrow][col++] = i + 'A';
if (col == ncol)
{
nrow++;
col = 0;
}
}
}
int cur = 0;
for (int i = 0; i < ncol; i++)
for (int j = 0; j <= nrow;j++)
if (grid[j][order[i]] != 0)
{
mapping[cur++] = grid[j][order[i]];
reversemap[grid[j][order[i]] - 'A'] = cur - 1;
}
getchar();
string line;
getline(cin, line);
int sz = (int)line.size();
for (int i = 0; i < sz; i++)
if (line[i] >= 'A' && line[i] <= 'Z')
cout << (char)(reversemap[line[i] - 'A'] + 'A');
else
cout << line[i];
cout << endl;
}
return 0;
}