Sunday, April 27, 2025

TWC318

Challenge Link

Task1

We return an array of runs of 3 or more characters:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub group_position{
  my @ret;
  push @ret,$1.$2 while($_[0] =~ m/(.)(\1{2,})/g);
  @ret
}

print show group_position('abccccd');
print show group_position('aaabcddddeefff');
print show group_position('abcdd');

Task2

We check if the two arrays are reverse of each other:

#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(first);

sub reverse_equals{
  my ($src,$target) = @_;
  my $from = first {$src->[$_] != $target->[$_]} 0..$#$src;
  return 1 unless defined $from;
  my $to = first {$src->[$_] != $target->[$_]} reverse $from..$#$src;
  foreach my $i(0..$to-$from){
    return 0 if $src->[$from+$i] != $target->[$to-$i]
  }
  1;
}

printf "%d\n",reverse_equals([3,2,1,4],[1,2,3,4]);
printf "%d\n",reverse_equals([1,3,4],[4,1,3]);
printf "%d\n",reverse_equals([2],[2]);

No comments:

Post a Comment