Skip to content

Instantly share code, notes, and snippets.

@nook-ru
Last active August 23, 2023 14:30
Show Gist options
  • Save nook-ru/b061de1bdcce939eea52406bd57f2054 to your computer and use it in GitHub Desktop.
Save nook-ru/b061de1bdcce939eea52406bd57f2054 to your computer and use it in GitHub Desktop.
const MORSE_CODE = [
'-.-.--' => '!',
'.-..-.' => '"',
'...-..-' => '$',
'.-...' => '&',
'.----.' => '\'',
'-.--.' => '(',
'-.--.-' => ')',
'.-.-.' => '+',
'--..--' => ',',
'-....-' => '-',
'.-.-.-' => '.',
'-..-.' => '/',
'-----' => '0',
'.----' => '1',
'..---' => '2',
'...--' => '3',
'....-' => '4',
'.....' => '5',
'-....' => '6',
'--...' => '7',
'---..' => '8',
'----.' => '9',
'---...' => ':',
'-.-.-.' => ';',
'-...-' => '=',
'..--..' => '?',
'.--.-.' => '@',
'.-' => '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',
'..--.-' => '_',
'...---...' => 'SOS',
];
<?php
require __DIR__ . '/dict.inc.php'
/**
function decode_morse_v1(string $code): string {
$words = explode(' ', $code);
$decodeWord = static function (string $code) {
$chars = explode(' ', $code);
return implode('', array_map(fn($char) => MORSE_CODE[$char], $chars));
};
return implode(' ', array_map($decodeWord, $words));
}
function decode_morse_v2(string $code): string {
$code = trim($code);
$decodeWord = fn($code) => implode('', array_map(fn($char) => MORSE_CODE[$char], array_filter(explode(' ', $code))));
return implode(' ', array_map($decodeWord, explode(' ', $code)));
}
**/
function decode_morse_optimal(string $code): string {
return strtr(trim($code), MORSE_CODE + [' ' => ' ',' ' => '']);
}
echo json_encode(decode_morse_optimal('.... . -.-- .--- ..- -.. .'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment