Skip to content

Instantly share code, notes, and snippets.

@XedinUnknown
Created August 20, 2018 12:54
Show Gist options
  • Save XedinUnknown/1fcd908fa3006338e6f4041fa5cf4eac to your computer and use it in GitHub Desktop.
Save XedinUnknown/1fcd908fa3006338e6f4041fa5cf4eac to your computer and use it in GitHub Desktop.
Morse Code Problem
function possibilities ($word) {
$tree = [
'children' => [
[
'symbol' => 'E',
'children' => [
[
'symbol' => 'I',
'children' => [
[
'symbol' => 'S',
'children' => [],
],
[
'symbol' => 'U',
'children' => [],
],
]
],
[
'symbol' => 'A',
'children' => [
[
'symbol' => 'R',
'children' => [],
],
[
'symbol' => 'W',
'children' => [],
],
]
],
],
],
[
'symbol' => 'T',
'children' => [
[
'symbol' => 'N',
'children' => [
[
'symbol' => 'D',
'children' => [],
],
[
'symbol' => 'K',
'children' => [],
],
]
],
[
'symbol' => 'M',
'children' => [
[
'symbol' => 'G',
'children' => [],
],
[
'symbol' => 'O',
'children' => [],
],
]
],
],
],
],
];
$word = str_split($word);
$possibilities = array();
$cur = [$tree];
for ($i = 0; $i < count($word); $i++) {
$newCur = [];
foreach ($cur as $_cur) {
if ($word[$i] === '.') {
$newCur[] = $_cur['children'][0];
continue;
}
if ($word[$i] === '-') {
$newCur[] = $_cur['children'][1];
continue;
}
$newCur = array_merge($newCur, $_cur['children']);
}
$cur = $newCur;
}
foreach ($cur as $_cur) {
$possibilities[] = $_cur['symbol'];
}
return $possibilities;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment