본문 바로가기
알고리즘/Codewars

[Codewars] Decode the Morse code (6 kyu) / JavaScript

by fluss 2022. 12. 12.

https://www.codewars.com/kata/54b724efac3d5402db00065e

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Part of Series 1/3
This kata is part of a series on the Morse code. After you solve this kata, you may move to the next one.
 

In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superseded by voice and digital data communication channels, it still has its use in some applications around the world.

The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−−   ·−−− ··− −·· ·.

 

NOTE: Extra spaces before or after the code have no meaning and should be ignored.

 

In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words.

 

Your task is to implement a function that would take the morse code as input and return a decoded human-readable string.

 

For example:

decodeMorse('.... . -.--   .--- ..- -.. .')
//should return "HEY JUDE"

NOTE: For coding purposes you have to use ASCII characters . and -, not Unicode characters.

 

The Morse code table is preloaded for you as a dictionary, feel free to use it:

  • Coffeescript/C++/Go/JavaScript/Julia/PHP/Python/Ruby/TypeScript: MORSE_CODE['.--']
  • C#: MorseCode.Get(".--") (returns string)
  • F#: MorseCode.get ".--" (returns string)
  • Elixir: @morse_codes variable (from use MorseCode.Constants). Ignore the unused variable warning for morse_codes because it's no longer used and kept only for old solutions.
  • Elm: MorseCodes.get : Dict String String
  • Haskell: morseCodes ! ".--" (Codes are in a Map String String)
  • Java: MorseCode.get(".--")
  • Kotlin: MorseCode[".--"] ?: "" or MorseCode.getOrDefault(".--", "")
  • Racket: morse-code (a hash table)
  • Rust: MORSE_CODE
  • Scala: morseCodes(".--")
  • Swift: MorseCode[".--"] ?? "" or MorseCode[".--", default: ""]
  • C: provides parallel arrays, i.e. morse[2] == "-.-" for ascii[2] == "C"
  • NASM: a table of pointers to the morsecodes, and a corresponding list of ascii symbols

All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly because otherwise the engine would simply ignore the tests, resulting in a "valid" solution.

 

Good luck!

After you complete this kata, you may try yourself at Decode the Morse code, advanced.

 

설명:

시리즈 1/3.
이 카타는 모스 부호 시리즈의 일부입니다. 이 카타를 해결한 후 다음 카타로 넘어갈 수 있습니다.
 
이 카타에서 간단한 모스 부호 디코더를 작성해야 합니다. 모스 부호는 현재 대부분이 음성 및 디지털 통신 채널로 대체되었지만, 여전히 전 세계의 일부 응용 프로그램에서 사용되고있습니다.

 

모스부호는 모든 문자를 "점"과 "대시"의 시퀀스로 인코딩합니다. 예를 들어, 글자 "A"는 ·−, 글자 Q는 −−·−로, 그리고 숫자 1은 ·−−−−로 코드화 됩니다. 모스부호는 대소문자를 신경 쓰지 않고 전통적으로 대문자가 사용됩니다. 메시지를 모스코 드로 작성할 때, 문자 코드를 구분하기 위해 하나의 공백을 사용하고, 단어를 구분하기 위해 3개의 공백을 사용합니다. 예를 들어 HEY JUDE 메시지의 모스부호는 ···· · −·−−   ·−−− ··− −·· ·입니다.

 

참고: 코드 앞뒤의 공백은 아무 의미가 없으니 무시하세요.

 

문자 숫자 그리고 몇몇 구두점 외에도 몇 가지 특별한 서비스 코드가 있는데 그중 가장 악명 높은 것은 국제 조난 신호로 알려진 (Titanic으로 처음 이슈가 된) SOS이고 ···−−−··· 로 코드화 됩니다. 이런 특별한 코드는 단일 특별 문자로 취급되며 일반적으로 별도의 단어로 전송됩니다.

 

모스 부호를 입력으로 받아 디코딩된 사람이 읽을 수 있는 문자열을 반환하는 함수를 구현하세요.

 

예시:

decodeMorse('.... . -.--   .--- ..- -.. .')
//should return "HEY JUDE"

참고: 코딩을 위해 유니코드 문자가 아닌 ASCII 문자 . 및 - 를 사용해야 합니다. 

 

모스 부호 테이블은 딕셔너리로 사전에 로드되어 있으니 자유롭게 사용하세요:

  • Coffeescript/C++/Go/JavaScript/Julia/PHP/Python/Ruby/TypeScript: MORSE_CODE['.--']
  • C#: MorseCode.Get(".--") (문자열 반환)
  • F#: MorseCode.get ".--" (문자영 반환)
  • Elixir: @morse_codes variable (MorseCode.Constants 사용). morse_codes에 대해 사용되지 않은 변수 경고는 더이상 사용되지 않고 오래된 솔루션에만 적용되므로 무시하세요.
  • Elm: MorseCodes.get : Dict String String
  • Haskell: morseCodes ! ".--" (Map String String에 코드가 있음)
  • Java: MorseCode.get(".--")
  • Kotlin: MorseCode[".--"] ?: "" 또는 MorseCode.getOrDefault(".--", "")
  • Racket: morse-code (해시 테이블)
  • Rust: MORSE_CODE
  • Scala: morseCodes(".--")
  • Swift: MorseCode[".--"] ?? "" 또는 MorseCode[".--", default: ""]
  • C: 병렬 배열 제공, 즉 morse[2] == "-.-" 는 ascii[2] == "C"
  • NASM: morsecodes에 대한 포인터의 테이블과 ascii 기호의 동등한 목록

 

모든 테스트 문자열은 유효한 모스 부호를 포함하고 있기 때문에 오류 및 예외 확인을 생략해도 됩니다. C#에서는, 솔루션 코드에서 예외가 발생하면 테스트가 실패하므로 이 점을 염두에 두세요. 그렇지 않으면 엔진이 단순히 테스트를 무시하여 "유효한" 솔루션이라는 결과가 나오기 때문입니다.

 

행운을 빌어요!

이 카타를 완료한 후에는, Decode the Morse code, advanced를 직접 시도해볼 수 있습니다.

 

풀이

morseCode를 3개의 공백을 기준으로 자르고 그 잘린 문자열을 공백을 기준으로 자른다. 그리고 그 문자열을 MORSE_CODE의 키로 해서 얻은 글자를 합려로 반환했다.

 

코드

decodeMorse = function(morseCode){
  // Your code here
  // You can use MORSE_CODE[morse]  
  morseCode = morseCode.trim().split('   ').map(el => el.split(' '));
  result = [];
  for(let i = 0; i < morseCode.length; i++){
    let str = [];
    for(let j = 0; j < morseCode[i].length; j++){
      str.push(MORSE_CODE[morseCode[i][j]]);
    }
    result.push((str.join('')));
  }
  return result.join(' ');
}

댓글