Monday, March 24, 2025

TWC314

Challenge Link

Task1

We look for common prefixes:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0 min);

sub equal_strings{
  my @lens = map{length} @_;
  my $sum = sum0 @lens;
  my $n = min @lens;
  foreach my $i(0..$n){
    if(!(substr($_[0],$i,1) eq substr($_[1],$i,1) &&
       substr($_[1],$i,1) eq substr($_[2],$i,1))){
      return $i == 0 ? -1 : $sum - 3 * $i
    }
  }
  $sum - 3 * $n
}

printf "%d\n",equal_strings('abc','abb','ab');
printf "%d\n",equal_strings('ayz','cyz','xyz');
printf "%d\n",equal_strings('yza','yzb','yzc');

Task2

We count sorted columns:
#!/usr/bin/env perl
use strict;
use warnings;

sub sort_column{
  my ($arr) = @_;
  my $ret = 0;
  foreach my $j(0..length($arr->[0])-1){
    foreach my $i(1..$#$arr){
      if(substr($arr->[$i],$j,1) lt substr($arr->[$i-1],$j,1)){
	$ret++;
	last
      }
    }
  }
  $ret
}

printf "%d\n",sort_column(['swpc','tyad','azbe']);
printf "%d\n",sort_column(['cba','daf','ghi']);
printf "%d\n",sort_column(['a','b','c']);

No comments:

Post a Comment