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 $#.

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 real life ranting 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