Last active
June 5, 2020 15:38
-
-
Save eurobob/bb2e6d11566997f9f51e0ad83b9edbd2 to your computer and use it in GitHub Desktop.
Morse code binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple morse code translation up to 3 levels deep with uncertainty allowance | |
* | |
* @example | |
* // returns [ 'K', 'O' ] | |
* node morsecode.js '-?-' | |
* | |
* @param {String} input Morse code string containing '-', '.' and '?' characters | |
* @returns {String[]} Array of possible value outcomes | |
* | |
*/ | |
class Node { | |
constructor(data) { | |
this.data = data; | |
this["."] = null; | |
this["-"] = null; | |
} | |
} | |
class BinarySearchTree { | |
constructor() { | |
this.root = new Node(null); | |
} | |
// Recursively populate tree sequentially | |
insert(data, root, index) { | |
if (index < data.length) { | |
root = new Node(data[index]); | |
root["."] = this.insert(data, root["."], 2 * index + 1); | |
root["-"] = this.insert(data, root["-"], 2 * index + 2); | |
} | |
return root; | |
} | |
traverse(signalArray, nodeArray) { | |
// Clone input | |
let nodes = [...nodeArray]; | |
for (const signal of signalArray) { | |
const nodePossibilities = []; | |
for (let x = 0; x < nodes.length; x++) { | |
if (signal === "?") { | |
// If signal is unknown, add both child nodes to array | |
const left = nodes[x]["."]; | |
const right = nodes[x]["-"]; | |
if (left) { | |
nodePossibilities.push(left); | |
} | |
if (right) { | |
nodePossibilities.push(right); | |
} | |
} else { | |
// If signal is known, add only that child node to array | |
const node = nodes[x][signal]; | |
if (node) { | |
nodePossibilities.push(node); | |
} | |
} | |
} | |
// Update node array | |
nodes = nodePossibilities; | |
} | |
// Return mapped possibilities | |
return nodes.map(({ data }) => data); | |
} | |
} | |
const alphabet = " ETIANMSURWDKGO".split(""); | |
const BST = new BinarySearchTree(); | |
BST.root = BST.insert(alphabet, BST.root, 0); | |
function possibilities(input) { | |
const value = BST.traverse(input.split(""), [BST.root]); | |
console.log(value); | |
} | |
const args = process.argv.slice(2); | |
possibilities(args[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment