Tuesday, July 16, 2024

TWC278

Challenge Link

Task1

We separate the alphas from digits in each word of the string and make a hash from it, then we sort that hash according to the values and return the result as a string:
#!/usr/bin/env perl
use strict;
use warnings;

sub sort_string{
  my %h = map{/(\w+)(\d+)/} split ' ',$_[0];
  join ' ',sort{$h{$a} <=> $h{$b}} keys %h
}

printf "%s\n",sort_string('and2 Raku3 cousins5 Perl1 are4');
printf "%s\n",
  sort_string('guest6 Python1 most4 the3 popular5 is2 language7');
printf "%s\n",sort_string('Challenge3 The1 Weekly2');

Task2

We match the desired part non-greedily, sort it, and substitute it in the given string:
#!/usr/bin/env perl
use strict;
use warnings;

sub reverse_string{
  $_[0] =~ s/(.*?$_[1])/join '',sort split '',$1/er
}

printf "%s\n",reverse_string('challenge','e');
printf "%s\n",reverse_string('programming','a');
printf "%s\n",reverse_string('champion','b');

No comments:

Post a Comment