Search Bar

You have received an encoded message from your friend. To decrypt the message you need to follow a few steps as mentioned.

 

Java Coding interview question: This kind of algorithm question in JAVA.

 

Hi, Programmers today we will look at one of the Coding Questions asked in the TestGorilla assessment for the Java Developer role.

Problem Statement: Decrypt the Encrypted message OR Decrypt the Encrypted Message using Java with the help of the given steps.

Decrypt the Encrypted message OR Decrypt the Encrypted Message using Java with the help of the given steps.


You have received an encoded message from your friend. To decrypt the message you need to follow a few steps as mentioned below.

1. Split the message in separate words using whitespace as a separator.

2. Create a key-value pair for each word where the key is the sum of all the digits present in that word and the value is the word after removing digits from encoded word. If there are no digits, assume key = 0 for that word.

3. Arrange the words based on the ascending order of their keys.

4. If multiple words have the same numeric key, keep the latter word in the output and discard the earlier words.

Input: This i1s m3y fir4st te5st m1es3sa5ge.

Output: This is my first test message.

Input: t2e1st This i1s f1irs1t

Output: This is first test

Code: 


package test.amol;

import java.util.*;

public class InterviewPrep {

public static void main(String[] args) {

String encodedMessage = "t2e1st This i1s f1irs1t";
String decryptedMessage = decryptMessage(encodedMessage);
System.out.println(decryptedMessage);

}

public static String decryptMessage(String encodedMessage) {
String[] words = encodedMessage.split("\\s+");
Map<Integer, String> wordMap = new HashMap<>();

for (String word : words) {
int key = calculateKey(word);
wordMap.put(key, word.replaceAll("\\d", ""));
}

TreeMap<Integer, String> sortedWordMap = new TreeMap<>(wordMap);

List<String> decryptedWords = new ArrayList<>(sortedWordMap.values());
//Collections.reverse(decryptedWords);

return String.join(" ", decryptedWords);
}

private static int calculateKey(String word) {
int key = 0;

for (char c : word.toCharArray()) {
if (Character.isDigit(c)) {
key += Character.getNumericValue(c);
}
}

return key;
}
}

Post a Comment

0 Comments