The weekly challenge 331 - Task 2: Buddy Strings
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-331/#TASK2 3 # 4 # Task 2: Buddy Strings 5 # ===================== 6 # 7 # You are given two strings, source and target. 8 # 9 # Write a script to find out if the given strings are Buddy Strings. 10 # 11 ## If swapping of a letter in one string make them same as the other then they 12 ## are `Buddy Strings`. 13 # 14 # 15 ## Example 1 16 ## 17 ## Input: $source = "fuck" 18 ## $target = "fcuk" 19 ## Output: true 20 ## 21 ## The swapping of 'u' with 'c' makes it buddy strings. 22 # 23 # 24 ## Example 2 25 ## 26 ## Input: $source = "love" 27 ## $target = "love" 28 ## Output: false 29 # 30 # 31 ## Example 3 32 ## 33 ## Input: $source = "fodo" 34 ## $target = "food" 35 ## Output: true 36 # 37 # 38 ## Example 4 39 ## 40 ## Input: $source = "feed" 41 ## $target = "feed" 42 ## Output: true 43 # 44 ############################################################ 45 ## 46 ## discussion 47 ## 48 ############################################################ 49 # 50 # We split one of the words (let's decide for the target, but 51 # we could equally use the source here) into individual characters. 52 # Then we just try to swap each character against each other, and if 53 # the resulting string matches the source, we return true. Then we 54 # swap back of course, jumping to the next pair of characters to 55 # swap. If we didn't find a true solution at the end, we can 56 # return false. 57 58 use v5.36; 59 60 buddy_strings("fuck", "fcuk"); 61 buddy_strings("love", "love"); 62 buddy_strings("fodo", "food"); 63 buddy_strings("feed", "feed"); 64 65 sub buddy_strings($source, $target) { 66 say "Input: \"$source\", \"$target\""; 67 my @t_chars = split //, $target; 68 foreach my $i (0..$#t_chars) { 69 foreach my $j ($i+1..$#t_chars) { 70 ($t_chars[$i], $t_chars[$j]) = ($t_chars[$j], $t_chars[$i]); 71 my $tmp = join("", @t_chars); 72 if($source eq $tmp) { 73 return say "Output: true"; 74 } 75 ($t_chars[$i], $t_chars[$j]) = ($t_chars[$j], $t_chars[$i]); 76 } 77 } 78 say "Output: false"; 79 }