RabbitFarm
2024-10-05
Maximum Jumble
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1: Third Maximum
You are given an array of integers, @ints. Write a script to find the third distinct maximum in the given array. If a third maximum doesn’t exist then return the maximum number.
The majority of the work can be done in a couple of lines. We need only sort the distinct integers in the list and then return either the third largest number or, if none exists, the largest.
-
sub third_maximum{
my %h;
do{ $h{$_} = undef } for
@_;
my
@sorted = sort {$b <=> $a} keys %h;
return $sorted[2] if
@sorted >= 3;
return $sorted[0];
}
◇
-
Fragment referenced in 2.
The rest of the code just tests this function.
-
MAIN:{
say third_maximum 5, 6, 4, 1;
say third_maximum 4, 5;
say third_maximum 1, 2, 2, 3;
}
◇
-
Fragment referenced in 2.
Sample Run
$ perl perl/ch-1.pl 4 5 1
Part 2: Jumbled Letters
Your task is to write a program that takes English text as its input and outputs a jumbled version
The rules for jumbling are given as follows:
- The first and last letter of every word must stay the same.
- The remaining letters in the word are scrambled in a random order (if that happens to be the original order, that is OK).
- Whitespace, punctuation, and capitalization must stay the same.
- The order of words does not change, only the letters inside the word.
Looking closer at these rules the main thing we need to concern ourselves with is jumbling the letters with the exception of the first and last. The use of map will ensure the words are processed in order. To make sure the first/last letters are unchanged also depends on detecting punctuation.
Punctuation is determined by a regex. We’ll keep track of the locations so we can add them back later, after jumbling.
Now that we have the punctuation accounted for let’s do the jumble. We’ll do this by generating permutations and randomly select one.
-
my $p = Algorithm::Permute->new(
[
@{$stripped}[1 ..
@{$stripped} - 2]]
);
my
@p;
if(
@{$stripped} > 2){
my
@r = $p->next();
{
push
@p, [
@r];
r = $p->next();
redo if
@r;
}
$stripped = [$stripped->[0] ,
{$p[rand
@p]} ,
$stripped->[
@{$stripped} - 1]];
}
$stripped = join q//,
@{$stripped};
◇
Finally, add the punctuation back in.
The rest of the code drives some tests.
-
MAIN:{
say q/in the ASCII range match all non-controls./;
say jumble qw/in the ASCII range match all non-controls./;
say q//;
say q/This handy module makes performing permutation.../;
say jumble qw/This handy module makes performing permutation.../;
}
◇
-
Fragment referenced in 9.
Sample Run
$ perl perl/ch-2.pl in the ASCII range match all non-controls. in the AISCI range macth all non-rloncots. This handy module makes performing permutation... Tihs handy mloude mkaes prifnremog prtaoimetun...
References
posted at: 21:02 by: Adam Russell | path: /perl | permanent link to this entry