perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 378 - Task 2: Sum of Words

  1 #!/usr/bin/env perl
  2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-378/#TASK2
  3 #
  4 # Task 2: Sum of Words
  5 # ====================
  6 #
  7 # You are given three strings consisting of lower case English letters ‘a’ to
  8 # ‘j’ only. The letter value of a = 0, b = 1, c = 3, etc.
  9 #
 10 # Write a script to find if sum of first two strings return the third string.
 11 #
 12 ## Example 1
 13 ##
 14 ## Input: $str1 = "acb", $str2 = "cba", $str3 = "cdb"
 15 ## Output: true
 16 ##
 17 ## $str1 = "acb" = 021
 18 ## $str2 = "cba" = 210
 19 ## $str3 = "cdb" = 231
 20 ## $str1 + $str2 = $str3
 21 #
 22 ## Example 2
 23 ##
 24 ## Input: $str1 = "aab", $str2 = "aac", $str3 = "ad"
 25 ## Output: true
 26 ##
 27 ## $str1 = "aab" = 001
 28 ## $str2 = "aac" = 002
 29 ## $str3 = "ad"  = 03
 30 #
 31 ## Example 3
 32 ##
 33 ## Input: $str1 = "bc", $str2 = "je", $str3 = "jg"
 34 ## Output: false
 35 ##
 36 ## $str1 = "bc" = 12
 37 ## $str2 = "je" = 94
 38 ## $str3 = "jg" = 96
 39 #
 40 ## Example 4
 41 ##
 42 ## Input: $str1 = "a", $str2 = "aaaa", $str3 = "aa"
 43 ## Output: true
 44 ##
 45 ## $str1 = "a"    = 0
 46 ## $str2 = "aaaa" = 0000
 47 ## $str3 = "aa"   = 00
 48 #
 49 ## Example 5
 50 ##
 51 ## Input: $str1 = "c", $str2 = "d", $str3 = "h"
 52 ## Output: false
 53 ##
 54 ## $str1 = "c" = 2
 55 ## $str2 = "d" = 3
 56 ## $str3 = "h" = 7
 57 #
 58 ## Example 6
 59 ##
 60 ## Input: $str1 = "gfi", $str2 = "hbf", $str3 = "bdhd"
 61 ## Output: true
 62 ##
 63 ## $str1 =  "gfi" =  658
 64 ## $str2 =  "hbf" =  715
 65 ## $str3 = "bdhd" = 1373
 66 #
 67 ############################################################
 68 ##
 69 ## discussion
 70 ##
 71 ############################################################
 72 #
 73 # We are bold enough to just skip leading 0's by turning a
 74 # simple string->number conversion into a "for each digit,
 75 # multiply by 10, then add the next digit" loop that starts
 76 # with 0. That also avoids accidental interpretation of a
 77 # number with leading zeroes as octal.
 78 
 79 use v5.36;
 80 
 81 sum_of_words("acb", "cba", "cdb");
 82 sum_of_words("aab", "aac", "ad");
 83 sum_of_words("bc", "je", "jg");
 84 sum_of_words("a", "aaaa", "aa");
 85 sum_of_words("c", "d", "h");
 86 sum_of_words("gfi", "hbf", "bdhd");
 87 
 88 sub sum_of_words($str1, $str2, $str3) {
 89     say "Input: \"$str1\", \"$str2\", \"$str3\"";
 90     my $num1 = str_to_num($str1);
 91     my $num2 = str_to_num($str2);
 92     my $num3 = str_to_num($str3);
 93     if ($num1 + $num2 == $num3) {
 94         say "Output: true";
 95     } else {
 96         say "Output: false";
 97     }
 98 }
 99 
100 sub str_to_num($str) {
101     my $num = 0;
102     foreach my $char (split //, $str) {
103         $num *= 10;
104         $num += (ord($char) - 97);
105     }
106     return $num;
107 }