RogerBW's Blog

Perl Weekly Challenge 25 11 September 2019

I've been doing the Perl Weekly Challenges. This one dealt with building long strings and the Chaocypher.

The first challenge was to generate the longest possible sequence from a list of Pokemon names, such that each name started with the character that ended the previous one.

Although it wasn't specified, I assumed that this was using each name only once in the sequence, otherwise there's a trivial infinite expansion if you can form a loop (minimally, by having one name that starts and ends with the same letter).

First step is to read the name list.

my $table;
open I,'<','names.txt';
while (<I>) {
  chomp;
  $_ =~ /^(.).*?(.)$/;
  $table->{$1}{$2}{$_}=1;
}
close I;

Then I use good old-fashioned recursion to look down each possible branch, thus generating an exhaustive search.

print join(' ',search($table,'')),"\n";

sub search {
  my $tab=shift;
  my $init=shift;
  my $m=0;
  my @out;
  my @initial;
  if (defined $init && $init) {
    @initial=($init);
  } else {
    @initial=sort keys %{$tab};
  }
  foreach my $initial (@initial) {
    foreach my $final (sort keys %{$tab->{$initial}}) {
      foreach my $candidate (sort keys %{$tab->{$initial}{$final}}) {
        my $tt=dclone($tab);
        delete $tt->{$initial}{$final}{$candidate};
        my @r=($candidate,search($tt,$final));
        my $l=scalar @r;
        if ($l > $m) {
          $m=$l;
          @out=@r;
        }
      }
    }
  }
  return @out;
}

The dclone (from Storable) is vital - it makes a copy of the data structure which can then be modified without changing the original.

I tried this in Perl 6, but while the perl5 version takes about five minutes for an exhaustive search on the test data, the perl6 had got nowhere after an hour. (This may have been because of an inefficient dclone-analogue.)

The other challenge was an implementation of Chaocipher, a substitution cipher that permutes its alphabets. This was relatively straightforward.

#print cipher([[split '','HXUCZVAMDSLKPEFJRIGTWOBNYQ'],
#        [split '','PTLNBQDEOYSFAVZKGJRIHWXUMC']],
#       'WELLDONEISBETTERTHANWELLSAID',
#       0),"\n";;

#print cipher([[split '','HXUCZVAMDSLKPEFJRIGTWOBNYQ'],
#        [split '','PTLNBQDEOYSFAVZKGJRIHWXUMC']],
#       'OAHQHCNYNXTSZJRRHJBYHQKSOUJY',
#       1),"\n";;

sub cipher {
  my $alpha=shift;
  my $in=shift;
  my $direction=shift; # 0 encipher, 1 decipher
  my $out;
  foreach my $inc (split '',$in) {
    my $m={map {$alpha->[1-$direction][$_] => $_} (0..$#{$alpha->[1-$direction]})};
    my $outc=$alpha->[$direction][$m->{$inc}];
    $out.=$outc;
    my @ctpt=($outc,$inc);
    if ($direction==1) {
      @ctpt=($inc,$outc);
    }
    # 1. Shift the entire left alphabet cyclically so the ciphertext
    # letter just enciphered is positioned at the zenith (i.e., position 1).
    $m={map {$alpha->[0][$_] => $_} 0..$#{$alpha->[0]}};
    push @{$alpha->[0]},@{$alpha->[0]};
    @{$alpha->[0]}=splice @{$alpha->[0]},$m->{$ctpt[0]},26;
    # 2. Extract the letter found at position zenith+1 (i.e., the
    # letter to the right of the zenith), taking it out of the
    # alphabet, temporarily leaving an unfilled ‘hole’.
    # 3. Shift all letters in positions zenith+2 up to, and
    # including, the nadir (zenith+13), moving them one position
    # to the left.
    my $temp=splice @{$alpha->[0]},1,1;
    # 4. Insert the just-extracted letter into the nadir position
    # (i.e., zenith+13).
    splice @{$alpha->[0]},13,0,$temp;
    # 1. Shift the entire right alphabet cyclically so the
    # plaintext letter just enciphered is positioned at the zenith.
    $m={map {$alpha->[1][$_] => $_} 0..$#{$alpha->[1]}};
    push @{$alpha->[1]},@{$alpha->[1]};
    @{$alpha->[1]}=splice @{$alpha->[1]},$m->{$ctpt[1]},26;
    # 2. Now shift the entire alphabet one more position to the
    # left (i.e., the leftmost letter moves cyclically to the far
    # right), moving a new letter into the zenith position.
    push @{$alpha->[1]},$alpha->[1][0];
    shift @{$alpha->[1]};
    # 3. Extract the letter at position zenith+2, taking it out of
    # the alphabet, temporarily leaving an unfilled ‘hole’.
    # 4. Shift all letters beginning with zenith+3 up to, and
    # including, the nadir (zenith+13), moving them one position
    # to the left.
    $temp=splice @{$alpha->[1]},2,1;
    # 5. Insert the just-extracted letter into the nadir
    # position (zenith+13).
    splice @{$alpha->[1]},13,0,$temp;
  }
  return $out;
}

Note that my shifts actually move all the letters, not just the ones up to the zenith, but that's OK because the later ones get moved back again when I insert the extracted letter.

Poked at this in Perl6 too, but I'm not good enough at data structures yet. (I like having both letter wheels as arrays within a single array, not as separate variables.)

Add A Comment

Your Name
Your Email
Your Comment

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action aeronautics aikakirja anecdote animation anime army astronomy audio audio tech base commerce battletech beer boardgaming book of the week bookmonth chain of command children chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup cycling dead of winter doctor who documentary drama driving drone ecchi economics espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 existential risk falklands war fandom fantasy film firefly first world war flash point food garmin drive gazebo geodata gin gurps gurps 101 harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo-nebula reread humour in brief avoid instrumented life kickstarter learn to play leaving earth linux mecha men with beards museum mystery naval non-fiction one for the brow opera perl perl weekly challenge photography podcast politics powers prediction privacy project woolsack pyracantha quantum rail ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance 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