perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 363 - Task 1: String Lie Detector

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-363/#TASK1
 3 #
 4 # Task 1: String Lie Detector
 5 # ===========================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script that parses a self-referential string and determines whether
10 # its claims about itself are true. The string will make statements about its
11 # own composition, specifically the number of vowels and consonants it
12 # contains.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "aa — two vowels and zero consonants"
17 ## Output: true
18 #
19 #
20 ## Example 2
21 ##
22 ## Input: $str = "iv — one vowel and one consonant"
23 ## Output: true
24 #
25 #
26 ## Example 3
27 ##
28 ## Input: $str = "hello - three vowels and two consonants"
29 ## Output: false
30 #
31 #
32 ## Example 4
33 ##
34 ## Input: $str = "aeiou — five vowels and zero consonants"
35 ## Output: true
36 #
37 #
38 ## Example 5
39 ##
40 ## Input: $str = "aei — three vowels and zero consonants"
41 ## Output: true
42 #
43 ############################################################
44 ##
45 ## discussion
46 ##
47 ############################################################
48 #
49 # We split the input into the string and the part that contains
50 # the amount of vowels and consonants.
51 # Then we first count the vowels and consonants in the string
52 # part. After that, we extract the counted numbers in the
53 # string. Now we only need to compare these numbers.
54 
55 use v5.36;
56 
57 string_lie_detector("aa - two vowels and zero consonants");
58 string_lie_detector("iv - one vowel and one consonant");
59 string_lie_detector("hello - three vowels and two consonants");
60 string_lie_detector("aeiou - five vowels and zero consonants");
61 string_lie_detector("aei - three vowels and zero consonants");
62 
63 sub string_lie_detector($str) {
64     say "Input: \"$str\"";
65     my ($string, $counts) = split / - /, $str;
66     my ($v_l, $c_l) = (0, 0);
67     my $map = {
68         "zero" => 0, "one" => 1, "two" => 2, "three" => 3, "four" => 4,
69         "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9,
70         "ten" => 10, "eleven" => 11, "twelve" => 12, "thirteen" => 13,
71         "fourteen" => 14, "fifteen" => 15, "sixteen" => 16,
72         "seventeen" => 17, "eighteen" => 18, "nineteen" => 19, "twenty" => 20
73     };
74 
75     foreach my $c (split //, $string) {
76         if($c =~ m/[aeiou]/) {
77             $v_l++;
78         } else {
79             $c_l++;
80         }
81     }
82     $counts =~ m/(\w+) vowels? and (\w+) consonants?/;
83     my ($v_r, $c_r) = ($1, $2);
84     if($v_l == $map->{$v_r} && $c_l == $map->{$c_r}) {
85         return say "Output: true";
86     }
87     say "Output: false";
88 }