Skip to content

Instantly share code, notes, and snippets.

@57op
Created February 29, 2020 18:08
Show Gist options
  • Save 57op/cf1048c55716c57059303d6487c852df to your computer and use it in GitHub Desktop.
Save 57op/cf1048c55716c57059303d6487c852df to your computer and use it in GitHub Desktop.
/*
* morse code [w/o spaces] isn't a prefix code.
* O(n * 2^n)
*/
const MORSE_CODE = {
'.-': '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'
}
function decode_morse(morse, results = [], path = []) {
if (morse.length === 0) {
results.push(path.join(''))
} else {
for (let i = 1; i <= morse.length; i++) {
const current_symbol = MORSE_CODE[morse.substring(0, i)]
const next_symbol = morse.substring(i)
if (current_symbol !== undefined) {
decode_morse(next_symbol, results, [...path, current_symbol])
}
}
}
return results
}
console.log(decode_morse('-..-.'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment