Peter’s blog ✴ Week 239 ✴ 16 October 2023
THE WEEKLY CHALLENGE
Pulling the strings
You are given two arrays of strings, @arr1 and @arr2. Write a script to find out if the word created by concatenating the array elements is the same.
Example 1 Input: @arr1 = ("ab", "c") @arr2 = ("a", "bc") Output: true Using @arr1, word1 => "ab" . "c" => "abc" Using @arr2, word2 => "a" . "bc" => "abc" Example 2 Input: @arr1 = ("ab", "c") @arr2 = ("ac", "b") Output: false Using @arr1, word1 => "ab" . "c" => "abc" Using @arr2, word2 => "ac" . "b" => "acb" Example 3 Input: @arr1 = ("ab", "cd", "e") @arr2 = ("abcde") Output: true Using @arr1, word1 => "ab" . "cd" . "e" => "abcde" Using @arr2, word2 => "abcde"
The handling of strings is one of Perl's strengths and allows this task to be solved
in essentially no lines of code at all. I just used the say statetment
that outputs the answer to join() each of the arrays, compare the results,
and output true or false depending on whether they match.
Perl core strength is in display for all to see. Cool attempt, well done.
#!/usr/bin/perl use v5.16; # The Weekly Challenge - 2023-10-16 use utf8; # Week 239 task 1 - Same string use strict; # Peter Campbell Smith use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge same_string(['ab', 'c'], ['a', 'bc']); same_string(['ac', 'b'], ['a', 'bc']); same_string(['the', 'cat', 'sat', 'on', 'the', 'mat'], ['thec', 'atsa', 'tont', 'hema', 't']); same_string(['the', 'cat', 'sat', 'on', 'the', 'mat'], ['the', 'dog', 'sat', 'on', 'the', 'rug']); sub same_string { # show input say qq[\nInput: \@arr1 = ('] . join(q[', '], @{$_[0]}) . q[')]; say qq[ \@arr2 = ('] . join(q[', '], @{$_[1]}) . q[')]; # show output by comparing the joins of the 2 arrays say qq[Output: ] . (join('', @{$_[0]}) eq join('', @{$_[1]}) ? 'true' : 'false'); }
4 lines of code
Input: @arr1 = ('ab', 'c') @arr2 = ('a', 'bc') Output: true Input: @arr1 = ('ac', 'b') @arr2 = ('a', 'bc') Output: false Input: @arr1 = ('the', 'cat', 'sat', 'on', 'the', 'mat') @arr2 = ('thec', 'atsa', 'tont', 'hema', 't') Output: true Input: @arr1 = ('the', 'cat', 'sat', 'on', 'the', 'mat') @arr2 = ('the', 'dog', 'sat', 'on', 'the', 'rug') Output: false
Any content of this website which has been created by Peter Campbell Smith is in the public domain