In: Computer Science
Write a function (in Javascript) called longestMorseCodeWords which takes in an array of strings. The output of longestMorseCodeWords should be an array of the strings that were passed in, but ordered by the length of their Morse Code equivalent in descending order. If the length of Morse Code is equal, order the words alphabetically.For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
let words = ["gin", "zen", "gig", "msg"]
longestMorseCodeWords(words)
The Morse Code equivalent of the words above is ["--...-.", "--...-.", "--...--.", "--...--."]. Ordering by length, it's [7, 7, 8, 8]. When we alphabetize based off of length in descending order, the output should be # ['gig', 'msg', 'gin', 'zen'].
JavaScript Code
function longestMorseCodeWords(words) {
// Inititalized Morse Code in an array
let morsecode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."];
let alphabets = "abcdefghijklmnopqrstuvwxyz";
let morseCodeArray = []; // Has Morse Code equivalent of the words
let morseCodeString = "";
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words[i].length; j++) {
morseCodeString += morsecode[alphabets.indexOf(words[i][j])];
}
morseCodeArray[i] = morseCodeString;
morseCodeString = "";
}
let morseCodeArrayLength = []; // Has Length of the morse code
for (let k = 0; k < morseCodeArray.length; k++) {
morseCodeArrayLength[k] = morseCodeArray[k].length;
}
let finalArray = []; // Has the final output;
let tempArray = [];
for (let m = Math.max.apply(null, morseCodeArrayLength); m >= Math.min.apply(null, morseCodeArrayLength); m--) {
while (morseCodeArrayLength.indexOf(m) != -1) { // Runs till there is not element of the same length
tempArray.push(words[morseCodeArrayLength.indexOf(m)]);
words.splice(morseCodeArrayLength.indexOf(m), 1);
morseCodeArrayLength.splice(morseCodeArrayLength.indexOf(m), 1);
}
tempArray.sort(); // Sorts Alphabetically
for (let l = 0; l < tempArray.length; l++) {
finalArray.push(tempArray[l]);
}
tempArray = [];
}
return finalArray; // Returns the final sorted array of words in the descending order of length
}
let words = ["zen","gig", "gin", "msg"]; // Input Words array
console.log(longestMorseCodeWords(words));
OUTPUT: