Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Question: which combinations (with a maximum length of 4) are unused in international Morse code?
// Question: which combinations with a maximum length of 4 are unused in international Morse code?
// http://en.wikipedia.org/wiki/Morse_code
var morseCodes = {
'.-': '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'
};
// Note: 4-signal Morse codes are more than 4 bit.
// With 4 signals (dot or dash), you get 30 combinations:
// 2 (length 1) + 4 (length 2) + 8 (length 3) + 16 (length 4)
var maxLen = 4;
for(var len = 1; len <= maxLen; len++) {
var combinations = Math.pow(2, len);
for(var x = 0; x < combinations; x++) {
var binary = x.toString(2);
// pad with zeros
while(binary.length < len) {
binary = '0' + binary;
}
// To replace multiple times, we need a regular expression
var code = binary.replace(/0/g, '.').replace(/1/g, '-');
var used = (code in morseCodes ? '' : ' UNUSED');
console.log(code+used);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.