forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtbash.java
More file actions
59 lines (43 loc) · 1.62 KB
/
Atbash.java
File metadata and controls
59 lines (43 loc) · 1.62 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
import java.util.ArrayList;
import java.util.List;
public class Atbash {
private static final int GROUP_SIZE = 5;
private static final String PLAIN = "abcdefghijklmnopqrstuvwxyz";
private static final String CIPHER = "zyxwvutsrqponmlkjihgfedcba";
public static String encode(String input) {
String encoded = stripInvalidCharacters(input).toLowerCase();
String cyphered = "";
for (char c : encoded.toCharArray()) {
cyphered += applyCipher(c);
}
return splitIntoFiveLetterWords(cyphered);
}
public static String decode(String input) {
String encoded = stripInvalidCharacters(input).toLowerCase();
String deciphered = "";
for (char c : encoded.toCharArray()) {
deciphered += applyCipher(c);
}
return deciphered;
}
private static String stripInvalidCharacters(String input) {
String filteredValue = "";
for (char c : input.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
filteredValue += c;
}
}
return filteredValue;
}
private static char applyCipher(char input) {
int idx = PLAIN.indexOf(input);
return idx >= 0 ? CIPHER.toCharArray()[idx] : input;
}
private static String splitIntoFiveLetterWords(String value) {
List<String> words = new ArrayList<>();
for (int i = 0; i < value.length(); i += GROUP_SIZE) {
words.add(i + GROUP_SIZE <= value.length() ? value.substring(i, i + GROUP_SIZE) : value.substring(i));
}
return String.join(" ", words);
}
}