Friday, May 23, 2025

TWC322

Challenge Link

Task1

We keep on grouping items from the right, then prepend the remainder and join the array with "-":
#!/usr/bin/env perl
use strict;
use warnings;

sub string_format{
  my $str = $_[0] =~ s/-//gr;
  my ($rem,@ret) = (length($str) % $_[1]);
  $rem and push @ret,substr($str,0,$rem,'');
  push @ret,substr($str,0,$_[1],'') while(length($str) > 0);
  join '-',@ret
}

printf "%s\n", string_format('ABC-D-E-F',3);
printf "%s\n", string_format('A-BC-D-E',2);
printf "%s\n", string_format('-A-B-CD-E',4);

Task2

We give each element its rank and put the ranks in their corresponding indices:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(uniq);
use Data::Show;

sub rank_array{
  my @uniq = sort{$a <=> $b} uniq @{$_[0]};
  my %h;
  @h{@uniq} = 1..@uniq;
  @h{@{$_[0]}}
}

print show rank_array([55,22,44,33]);
print show rank_array([10,10,10]);
print show rank_array([5,1,1,4,3]);

No comments:

Post a Comment