RogerBW's Blog

Perl Weekly Challenge 36: VINs and Knapsacks 05 December 2019

I’ve been doing the Perl Weekly Challenges. Last week's was about validating VINs and solving the knapsack problem.

For the VINs, there's a set length, an allowed character set, and an optional check digit, all laid out in Wikipedia.

Each allowed character (alphanumeric less I, O and Q) has a defined value for checksumming, and each place in the code has a weight, so we build those tables first.

my %cvalue;
map {$cvalue{$_}=$_} (0..9);
my $base=ord('A');
foreach my $char ('A'..'H','J'..'N','P','R') {
  $cvalue{$char}=(ord($char)-$base)%9+1;
}
foreach my $char ('S'..'Z') {
  $cvalue{$char}=(ord($char)-$base)%9+2;
}
my $valid=join('',keys %cvalue);

my @weight=reverse (2..9,0,10,2..8);

Do the basic tests on each VIN candidate before invoking the checksum algorithm.

foreach my $vin (@ARGV) {
  unless (length($vin)==17) {
    print "$vin is not 17 characters\n";
    next;
  }
  unless ($vin =~ /^[$valid]*$/) {
    print "$vin contains invalid characters\n";
    next;
  }

The checksum just multiplies each digit by its weight, then takes the total modulo 11, just like ISBNs. But unlike ISBNs it's not compulsory; many car-makers outside North America don't bother to calculate it.

  my $check=0;
  foreach my $ix (0..16) {
    $check+=$cvalue{substr($vin,$ix,1)}*$weight[$ix];
  }
  $check%=11;
  if ($check==10) {
    $check='X';
  }
  if (substr($vin,8,1) ne $check) {
    print "$vin does not pass check-digit verification (may be valid non-NA)\n";
    next;
  }
  print "$vin is valid.\n";
}

This is harder work in Perl6 because of the way lists are built up:

for (slip('A'..'H'),slip('J'..'N'),'P','R') -> $char {

and because of the way regexps are interpolated:

my $valid='^<[' ~ join('',keys %cvalue) ~ ']>*$';

[...]

unless ($vin ~~ /<$valid>/) {

but is otherwise basically the same.

The other half of the challenge was to solve a 0-1 knapsack problem. I decided not to get cunning, and simply worked up an O(2^N) solution.

my %box=(
  R => {w => 1, v => 1},
  B => {w => 1, v => 2},
  G => {w => 2, v => 2},
  Y => {w => 12, v => 4},
  P => {w => 4, v => 10},
    );

my @k=keys %box;
my @v=map {2**$_} (0..$#k);
my $maxw=15;
my $maxb=scalar @k;

This option is set for the constrained version ("you may take no more than N boxes").

# $maxb=3;

my $bestv=0;
my $bestw=0;
my $bestid=0;

We generate each possible combination of boxes and calculate its weight and value, abandoning it if the count of boxes or the total weight becomes too high. We keep the "best" solution; if there's a tie on value, the heavier one is preferred (though this is arbitrary).

foreach my $map (1..2**(scalar @k)-1) {
  my $b=0;
  my $v=0;
  my $w=0;
  foreach my $ci (0..$#k) {
    if ($map & $v[$ci]) {
      $v+=$box{$k[$ci]}{v};
      $w+=$box{$k[$ci]}{w};
      $b++;
    }
    if ($b>$maxb || $w>$maxw) {
      $v=-1;
      last;
    }
  }
  if ($v>0) {
    if ($v>$bestv || ($v==$bestv && $w>$maxw)) {
      $bestv=$v;
      $bestw=$w;
      $bestid=$map;
    }
  }
}

foreach my $ci (0..$#k) {
  if ($bestid & $v[$ci]) {
    print $k[$ci],"\n";
  }
}
print "$bestv in $bestw\n";

Perl6 is functionally identical, but one needs to use .elems and .end rather than scalar and $#.

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