Skip to content

Commit 549a27a

Browse files
Add bruteforce to the caesar cipher (TheAlgorithms#2887)
1 parent 32cdf02 commit 549a27a

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/main/java/com/thealgorithms/ciphers/Caesar.java

+25-3
Original file line numberDiff line numberDiff line change
@@ -91,28 +91,50 @@ private static boolean IsCapitalLatinLetter(char c) {
9191
private static boolean IsSmallLatinLetter(char c) {
9292
return c >= 'a' && c <= 'z';
9393
}
94+
/**
95+
* @return string array which contains all the possible decoded combination.
96+
*/
97+
public static String[] bruteforce(String encryptedMessage) {
98+
String[] listOfAllTheAnswers = new String[27];
99+
for (int i=0; i<=26; i++) {
100+
listOfAllTheAnswers[i] = decode(encryptedMessage, i);
101+
}
102+
103+
return listOfAllTheAnswers;
104+
}
94105

95106
public static void main(String[] args) {
96107
Scanner input = new Scanner(System.in);
108+
int shift = 0;
97109
System.out.println("Please enter the message (Latin Alphabet)");
98110
String message = input.nextLine();
99111
System.out.println(message);
100-
System.out.println("Please enter the shift number");
101-
int shift = input.nextInt() % 26;
102-
System.out.println("(E)ncode or (D)ecode ?");
112+
System.out.println("(E)ncode or (D)ecode or (B)ruteforce?");
103113
char choice = input.next().charAt(0);
104114
switch (choice) {
105115
case 'E':
106116
case 'e':
117+
System.out.println("Please enter the shift number");
118+
shift = input.nextInt() % 26;
107119
System.out.println(
108120
"ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle
109121
break;
110122
case 'D':
111123
case 'd':
124+
System.out.println("Please enter the shift number");
125+
shift = input.nextInt() % 26;
112126
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift));
127+
break;
128+
case 'B':
129+
case 'b':
130+
String[] listOfAllTheAnswers = bruteforce(message);
131+
for (int i =0; i<=26; i++) {
132+
System.out.println("FOR SHIFT " + String.valueOf(i) + " decoded message is " + listOfAllTheAnswers[i]);
133+
}
113134
default:
114135
System.out.println("default case");
115136
}
137+
116138
input.close();
117139
}
118140
}

0 commit comments

Comments
 (0)