Untitled
unknown
plain_text
a year ago
3.0 kB
8
Indexable
public class CaesarCipherDecoder {
public static String decodeMessage(String encodedMessage, int n) {
String decodedMessage = "";
// Calculate the sum of positions of letters
int sumOfPositions = 0;
for (int i = 0; i < encodedMessage.length(); i++) {
char ch = encodedMessage.charAt(i);
if (Character.isLetter(ch)) {
sumOfPositions += getCharacterPosition(ch);
}
}
// Reduce the sum to a single digit
int reducedSum = reduceToSingleDigit(sumOfPositions);
// Add the decoding number (n)
int finalValue = reducedSum + n;
// Wrap the finalValue around to stay between 1 and 9
if (finalValue < 1) {
finalValue = 9 + finalValue;
} else if (finalValue > 9) {
finalValue = finalValue % 9;
}
// Decode the message by subtracting finalValue from each letter's position
for (int i = 0; i < encodedMessage.length(); i++) {
char ch = encodedMessage.charAt(i);
if (Character.isLetter(ch)) {
decodedMessage += decodeCharacter(ch, finalValue);
} else {
decodedMessage += ch;
}
}
return decodedMessage;
}
// Get the position of the character in the alphabet (A=1, Z=26)
private static int getCharacterPosition(char ch) {
if (Character.isUpperCase(ch)) {
return ch - 'A' + 1;
} else {
return ch - 'a' + 1;
}
}
// Reduce a number to a single digit by summing its digits
private static int reduceToSingleDigit(int number) {
while (number >= 10) {
number = sumDigits(number);
}
return number;
}
// Helper method to sum digits of a number
private static int sumDigits(int number) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
// Decode a single character based on the final value
private static char decodeCharacter(char ch, int finalValue) {
int position = getCharacterPosition(ch);
// Subtract the finalValue from the position
int newPosition = position - finalValue;
// Wrap the position around if necessary
if (newPosition < 1) {
newPosition = 26 + newPosition;
}
// Return the decoded character
if (Character.isUpperCase(ch)) {
return (char) ('A' + newPosition - 1);
} else {
return (char) ('a' + newPosition - 1);
}
}
public static void main(String[] args) {
// Input and decoding number
String encodedMessage = "Zkrkxoq Gigjkse";
int decodingNumber = -21;
// Decoding the message
String decodedMessage = decodeMessage(encodedMessage, decodingNumber);
System.out.println("Decoded Message: " + decodedMessage);
}
}Editor is loading...
Leave a Comment