25 July 2025 | Challenge 331 |
The Last Buddy
Task 1: Last Word
Submitted by: Mohammad Sajid Anwar
You are given a string.
Write a script to find the length of last word in the given string.
Example 1
Input: $str = "The Weekly Challenge"
Output: 9
Example 2
Input: $str = " Hello World "
Output: 5
Example 3
Input: $str = "Let's begin the fun"
Output: 3
Solution
Globally match words in list context and take the difference between the last match’s end and start offset. Return zero if there is no word match.
use strict;
use warnings;
sub llw {
() = shift =~ /\w+/g or return 0;
$+[0] - $-[0];
}
See the full solution to task 1.
Task 2: Buddy Strings
Submitted by: Mohammad Sajid Anwar
You are given two strings, source
and target
.
Write a script to find out if the given strings are Buddy Strings
.
If swapping of a letter in one string make them same as the other then they are
Buddy Strings
.
Example 1
Input: $source = "fuck"
$target = "fcuk"
Output: true
The swapping of 'u' with 'c' makes it buddy strings.
Example 2
Input: $source = "love"
$target = "love"
Output: false
Example 3
Input: $source = "fodo"
$target = "food"
Output: true
Example 4
Input: $source = "feed"
$target = "feed"
Output: true
Solution
There are two principal possibilities for Buddy Strings:
source
andtarget
are equal and contain at least one duplicate character- or the number of positions where
source
andtarget
disagree is exactly two and the characters at these positions are swapped
Using PDL
for the implementation:
The two strings are converted to a 2-d ndarray holding the code points and a 1-d ndarray is calculated holding the indices of differing characters.
Handling the described cases then becomes almost straightforward:
- two characters differ if their
xor
‘ed values are nonzero - two strings are equal if they have no differing characters
- a string has duplicate characters if the number of unique characters is less than the total number of characters
- swapping two characters can be regarded as reversing a string of length two.
use strict;
use warnings;
use PDL v2.100; # has bxorover
use PDL::NiceSlice;
sub buddy_strings {
my $s = long map [map ord, split //], @_;
my $diff = which $s->xchg(0, 1)->bxorover;
$diff->isempty && $s(,0)->uniq->dim(0) < $s->dim(0) ||
$diff->nelem == 2 && all $s($diff,0) == $s($diff(-1:0),1);
}
See the full solution to task 2.
If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.