Skip to content

Instantly share code, notes, and snippets.

@hadaytullah
Last active Oct 25, 2019
Embed
What would you like to do?
Morse code algorithm in PHP
<? php
class MorseNode {
private $value;
private $leftNode;
private $rightNode;
function __construct($value, $leftNode, $rightNode){
$this->value = $value;
$this->leftNode = $leftNode;
$this->rightNode = $rightNode;
}
function getLeftNode(){
return $this->leftNode;
}
function getRightNode(){
return $this->rightNode;
}
function getValue(){
return $this->value;
}
}
function traverse($node, $signalsList, &$result){
//exit conditions
if(count($signalsList) == 0 ){
array_push($result,$node[0]);
return;
}
if($node[1] == null and $node[2] == null){
array_push($result,$node[0]);
return;
}
//normal flow
$signalBit = array_shift($signalsList);
switch($signalBit){
case ".": //left, 1 index
if($node[1] != null){ //leaf check
traverse($node[1],$signalsList, $result);
}
break;
case "-": //right, 2 index
if($node[2] != null){ //leaf check
traverse($node[2],$signalsList, $result);
}
break;
case "?":
if($node[1] != null){ //leaf check
traverse($node[1],$signalsList, $result);
}
if($node[2] != null){ //leaf check
traverse($node[2],$signalsList, $result);
}
break;
}
}
function possibilities ($signals) {
// the class declared above MorseNode can be used to make a more verbose but a bit slow version of the tree
// this Array form is a compact version, I will use this for efficiency reason
$morseTree = ["start",["E",["I",["S",null,null],["U",null,null]],["A",["R",null,null],["W",null,null]]],["T",["N",["D",null,null],["K",null,null]],["M",["G",null,null],["O",null,null]]]];
$signalList = str_split($signals);
$result = [];
traverse($morseTree, $signalList, $result);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment