-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
KeywordTranspositionCipher.java
80 lines (78 loc) · 1.99 KB
/
KeywordTranspositionCipher.java
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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) throws IOException{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(scan.readLine());
for(int i=0;i<T;i++){
String code = scan.readLine();
String text[] = scan.readLine().split(" ");
//int N = 0;
boolean record[] = new boolean[26];
String original = "";
for(int j=0;j<code.length();j++)
if(!record[code.charAt(j)-65]){
record[code.charAt(j)-65] = true;
original+=(code.charAt(j));
}
int cols = original.length();
int rows = 26/cols;
if(26%cols != 0)
rows++;
String matrix[] = new String[rows];
int index = 0;
matrix[0] = original;
int count = cols;
for(int j=1;j<rows && count<26;j++){
String temp = "";
for(int k=0;k<cols && count<26;k++)
if(record[index]){
k--;
index++;
}
else{
record[index] = true;
temp+=((char)(index+65));
index++;
count++;
}
matrix[j] = temp;
}
String complete = "";
char sorted[] = original.toCharArray();
int indices[] = new int[cols];
for(int j=0;j<cols;j++)
indices[j] = j;
for(int j=0;j<cols;j++){
int min = j;
for(int k=j+1;k<cols;k++)
if(sorted[k]<sorted[min])
min = k;
char t = sorted[min];
sorted[min] = sorted[j];
int te = indices[min];
indices[min] = indices[j];
indices[j] = te;
}
for(int j=0;j<cols;j++){
int col = indices[j];
for(int k=0;k<rows && col<matrix[k].length();k++){
complete+=(matrix[k].charAt(col));
}
}
char decryption_code[] = new char[26];
for(int j=0;j<26;j++)
decryption_code[complete.charAt(j)-65] = (char)(65+j);
for(int j=0;j<text.length;j++){
for(int k=0;k<text[j].length();k++){
System.out.print(decryption_code[text[j].charAt(k)-65]);
}
System.out.print(" ");
}
System.out.println();
}
}
}