Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package programming.set9.morses;
- import java.util.Arrays;
- import java.util.HashMap;
- public class MorseCoder {
- static String[] letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
- "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
- static String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
- "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
- "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" };
- static HashMap<String, String> letterToMorse = new HashMap<String, String>();
- static HashMap<String, String> morseToLetter = new HashMap<String, String>();
- public void run() {
- System.out.println(letters);
- }
- /**
- * Returns a new string which is the Morse code version of the input string.
- * Each word in the output will be on a separate line. The Morse representation
- * of each character of the input string is separated from the next by a space
- * character in the output string.
- *
- * @param input the input string.
- * @return the Morse code version of the input string, ignoring all characters
- * in the input string that cannot be represented in international Morse
- * code.
- */
- public static String encode(String input) {
- String temp = "";
- for (int i = 0; i < letters.length; i++) {
- letterToMorse.put(letters[i], morse[i]);
- }
- String trimmed = input.trim().replaceAll(" +", " ");
- trimmed = trimmed.toUpperCase();
- String encoded = "";
- String[] words = trimmed.split("\\s");
- for (String word : words) {
- encoded += "\n";
- for (int i = 0; i < word.length(); i++) {
- boolean result = Arrays.stream(letters).anyMatch(String.valueOf(word.charAt(i))::equals);
- if (result) {
- encoded += letterToMorse.get(String.valueOf(word.charAt(i))) + " ";
- }else {
- }
- }
- }
- return encoded.substring(1);
- }
- /**
- * Returns a new string which is the natural-language version of the input
- * string, which is assumed to be in Morse code format as produced by the encode
- * method.
- *
- * @param input morse code input string.
- * @return natural language version or {@code null} if the input string could
- * not be properly parsed.
- */
- public static String decode(String input) {
- for (int i = 0; i < letters.length; i++) {
- morseToLetter.put(morse[i], letters[i]);
- }
- String decoded = "";
- String trimmed = input.trim().replaceAll(" +", " ");
- String[] words = trimmed.split("\\s{2}");
- for (String word : words) {
- decoded += " ";
- String[] letters = word.split("\\s");
- for (String letter : letters) {
- decoded += morseToLetter.get(letter);
- }
- }
- return decoded.substring(1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement