RogerBW's Blog

Perl Weekly Challenge 35: Binary Morse Code 28 November 2019

I’ve been doing the Perl Weekly Challenges. Last week's was about encoding and decoding to a binary representation of Morse code.

This isn't one I've met before: a dot is 1, a dash is 111, an inter-dot/dash gap is 0, an inter-letter gap is 000, and an inter-word gap is 0000000.

The first step was to get the code table into memory; in perl5 I pulled it from a __DATA__ block, in perl6 I just defined it as a hash, but in each case it's a set of letter keys to dot/underscore values.

Next build a binary encoding table:

my %e;
foreach my $char (keys %t) {
  $e{$char}=join('0',map {{'.' => '1',
                           '_' => '111'}->{$_}}
                     split '',$t{$char});
}

Sanitise the input to the allowed character set (things for which encodings exist, and spaces):

my $chars=join('',keys %t);

my @in;
while (<>) {
  chomp;
  my $t=uc($_);
  $t =~ s/[^ $chars]//g;
  push @in,$t;
}

Then encode, building up words from characters and the message from words.

my $m=join(' ',@in);
my @l;
foreach my $word (split ' ',$m) {
  my @w;
  foreach my $char (split '',$word) {
    push @w,$e{$char};
  }
  push @l,join('000',@w);
}
print join('0000000',@l),"\n";

Perl6 is very similar, except that its split puts spurious empty strings at the beginning and end of the output list; it may well be that comb is a better option here, but it looks distinctly fiddly.

To decode, I build a decoding table:

my %d;
foreach my $char (keys %t) {
  $d{join('0',map {{'.' => '1',
                    '_' => '111'}->{$_}}
              split '',$t{$char})}=$char;
}

Then take the message, break it down to words and to characters, then decode individual characters as far as possible. Perl6 varies only in details of syntax.

my @in;
while (<>) {
  chomp;
  push @in,$_;
}
my $m=join('',@in);

my @m;
foreach my $word (split /0000000+/,$m) {
  my @w;
  foreach my $char (split /000+/,$word) {
    push @w,($d{$char} or '?');
  }
  push @m,join('',@w);
}
print join(' ',@m),"\n";

I also wrote a program to make random substitutions into the bit stream to see how the decoder would cope with corruption; it seems to do reasonably well, given the lack of redundancy in the encoding.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1