perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 373 - Task 1: Equal List

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-373/#TASK1
 3 #
 4 # Task 1: Equal List
 5 # ==================
 6 #
 7 # You are given two arrays of strings.
 8 #
 9 # Write a script to return true if the two given array represent the same
10 # strings otherwise false.
11 #
12 ## Example 1
13 ##
14 ## Input: @arr1 = ("a", "bc")
15 ##        @arr2 = ("ab", "c")
16 ## Output: true
17 ##
18 ## Array 1: "a" + "bc" = "abc"
19 ## Array 2: "ab" + "c" = "abc"
20 #
21 ## Example 2
22 ##
23 ## Input: @arr1 = ("a", "b", "c")
24 ##        @arr2 = ("a", "bc")
25 ## Output: true
26 ##
27 ## Array 1: "a" + "b" + "c" = "abc"
28 ## Array 2: "a" + "bc" = "abc"
29 #
30 ## Example 3
31 ##
32 ## Input: @arr1 = ("a", "bc")
33 ##        @arr2 = ("a", "c", "b")
34 ## Output: false
35 ##
36 ## Array 1: "a" + "bc" = "abc"
37 ## Array 2: "a" + "c" + "b" = "acb"
38 #
39 ## Example 4
40 ##
41 ## Input: @arr1 = ("ab", "c", "")
42 ##        @arr2 = ("", "a", "bc")
43 ## Output: true
44 ##
45 ## Array 1: "ab" + "c" + "" = "abc"
46 ## Array 2: ""  + "a" + "bc" = "abc"
47 #
48 ## Example 5
49 ##
50 ## Input: @arr1 = ("p", "e", "r", "l")
51 ##        @arr2 = ("perl")
52 ## Output: true
53 ##
54 ## Array 1: "p" + "e" + "r" + "l" = "perl"
55 ## Array 2: "perl"
56 #
57 ############################################################
58 ##
59 ## discussion
60 ##
61 ############################################################
62 #
63 # We just need to join the elements of each array into a string. Then
64 # we compare the strings to see whether they are the same.
65 #
66 use v5.36;
67 
68 equal_list(["a", "bc"], ["ab", "c"]);
69 equal_list(["a", "b", "c"], ["a", "bc"]);
70 equal_list(["a", "bc"], ["a", "c", "b"]);
71 equal_list(["ab", "c", ""], ["", "a", "bc"]);
72 equal_list(["p", "e", "r", "l"], ["perl"]);
73 
74 sub equal_list($arr1, $arr2) {
75     say "Input: (\"" . join("\", \"", @$arr1) . "\"), (\"" . join("\", \"", @$arr2) . "\")";
76     my $str1 = join("", @$arr1);
77     my $str2 = join("", @$arr2);
78     if($str1 eq $str2) {
79         say "Output: true";
80     } else {
81         say "Output: false";
82     }
83 }