Tuesday, July 21, 2026

TWC383

Challenge Link

Task1

We check if elements belong to the same synonym group:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub similar_list{
  return 0 unless @{$_[0]} == @{$_[1]};
 OUTER:
  foreach my $i(0..$#{$_[0]}){
    next OUTER if $_[0]->[$i] eq $_[1]->[$i];
    foreach my $sub(@{$_[2]}){
      next OUTER if in($_[0]->[$i],$sub) &&
	in($_[1]->[$i],$sub)
      }
    return 0
  }
  1
}

sub in{
  my ($e,$l) = @_;
  grep {$_ eq $e} @$l
}

is similar_list(['great','acting'],
		['fine','drama'],
		[['great','fine'],
		 ['acting','drama']]),1,'Example 1';
is similar_list(['apple','pie'],
		['banana','pie'],
		[['apple','peach'],
		 ['peach','banana']]),0,'Example 2';
is similar_list(['perl4','python'],
		['raku','python'],
		[['perl4','perl5','raku']]),1,'Example 3';
is similar_list(['enjoy','challenge'],
		['love', 'weekly', 'challenge'],
		[['enjoy','love']]),0,'Example 4';
is similar_list(['fast','car'],
		['quick','vehicle'],
		[['quick','fast'],['vehicle','car']]),1,'Example 5';
done_testing();

Task2

We make the colors web safe according to the given rules:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub nearest_rgb{
  my @web_safe = (0,51,102,153,204,255);
  my ($r,$g,$b) = map hex,$_[0] =~ /#(..)(..)(..)/;
  my $safe = '#';
  foreach my $c($r,$g,$b) {
    my $best = 0;
    foreach my $s(@web_safe){
      $best = $s if abs($c - $s) < abs($best - $c)
    }
    $safe .= sprintf '%02X',$best
  }
  $safe
}

is nearest_rgb('#F4B2D1'),'#FF99CC','Example 1';
is nearest_rgb('#15E6E5'),'#00FFCC','Example 2';
is nearest_rgb('#191A65'),'#003366','Example 3';
is nearest_rgb('#2D5A1B'),'#336633','Example 4';
is nearest_rgb('#00FF66'),'#00FF66','Example 5';

done_testing();

No comments:

Post a Comment