december_adventure_2023

December Adventure (2023)
git clone https://git.eamoncaddigan.net/december_adventure_2023.git
Log | Files | Refs | README

commit 5a1bb738f044777738bcdb32d10d7280a598b581
parent 009e7e6787cb153c0c5ffe1eea9a1991181873ba
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date:   Wed, 13 Dec 2023 20:28:25 -0800

R script to encode morse code

The approach is better described on the web than it is in the code:
<https://www.eamoncaddigan.net/december-adventure/2023-12/>

Diffstat:
Amorseencode.R | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 58 insertions(+), 0 deletions(-)

diff --git a/morseencode.R b/morseencode.R @@ -0,0 +1,58 @@ +#!/usr/bin/env Rscript + +suppressPackageStartupMessages(library(dplyr)) + +# Mapping from characters to morse code +morse_dat <- tibble::tribble( + ~char, ~morse, + "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", "--.." +) + +# Pack a Morse Code representation of a character into a short (16-bit) +# integer. `.` becomes `01`, `-` becomes `11`, signals are encoded with the +# early bits lower than later bits (they're "backwards". +encode_morse <- function(morse_sequence) { + sum(((strsplit(morse_sequence, "")[[1]] == "-") * 2 + 1) + * 4^(seq(0, nchar(morse_sequence)-1))) +} + +morse_dat <- morse_dat |> + mutate(morse_int = as.integer(vapply(morse, encode_morse, double(1))), + morse_hex = sprintf('%0.4x', morse_int)) + +cat(morse_dat$morse_hex, sep = '\n')