Tap code is a way to communicate messages via a series of taps (or knocks) for each letter in the message. Letters are arranged in a 5×5 polybius square, with the letter “K” being moved to the space with “C”.
1 2 3 4 5
1 A B C\K D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z
Each letter is translated by tapping out the row and column number that the letter appears in, leaving a short pause in-between. If we use “.” for each tap, and a single space to denote the pause:
text = "break"
"B" = (1, 2) = ". .."
"R" = (4, 2) = ".... .."
"E" = (1, 5) = ". ....."
"A" = (1, 1) = ". ."
"K" = (1, 3) = ". ..."
Another space is added between the groups of taps for each letter to give the final code:
"break" = ". .. .... .. . ..... . . . ..."
Write a function that returns the tap code if given a word, or returns the translated word (in lower case) if given the tap code.
Examples
tapCode("break") ➞ ". .. .... .. . ..... . . . ..."
tapCode(".... ... ... ..... . ..... ... ... .... ....") ➞ "spent"
Notes
For more information on tap code, please see the resources section. The code was widely used in WW2 as a way for prisoners to communicate.
Problem URL
Solution:
Its brute-force one, elegant solution can be derived but I am just too stupid and lazy atm🤪
function tapCode(text) {
const morseCode = {
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: "..... ....."
};
const revMorse = {
". .": "a",
". ..": "b",
". ...": "c",
". ....": "d",
". .....": "e",
".. .": "f",
".. ..": "g",
".. ...": "h",
".. ....": "i",
".. .....": "j",
"... .": "l",
"... ..": "m",
"... ...": "n",
"... ....": "o",
"... .....": "p",
".... .": "q",
".... ..": "r",
".... ...": "s",
".... ....": "t",
".... .....": "u",
"..... .": "v",
"..... ..": "w",
"..... ...": "x",
"..... ....": "y",
"..... .....": "z"
};
sol = "";
if (text.indexOf(".") < 0) {
for (ch of text.split("")) {
sol += morseCode[ch];
sol += " ";
}
} else {
let str = text.split(" ");
for (let i = 0; i < str.length; i += 2) {
console.log([str[i] + " " + str[i + 1]]);
sol += revMorse[str[i] + " " + str[i + 1]];
}
}
return sol.trim();
}