The weekly challenge 332 - Task 2: Odd Letters
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-332/#TASK2 3 # 4 # Task 2: Odd Letters 5 # =================== 6 # 7 # You are given a string. 8 # 9 # Write a script to find out if each letter in the given string appeared odd number of times. 10 # 11 ## Example 1 12 ## 13 ## Input: $str = "weekly" 14 ## Output: false 15 ## 16 ## w: 1 time 17 ## e: 2 times 18 ## k: 1 time 19 ## l: 1 time 20 ## y: 1 time 21 ## 22 ## The letter 'e' appeared 2 times i.e. even. 23 # 24 # 25 ## Example 2 26 ## 27 ## Input: $str = "perl" 28 ## Output: true 29 # 30 # 31 ## Example 3 32 ## 33 ## Input: $source = "challenge" 34 ## Output: false 35 # 36 ############################################################ 37 ## 38 ## discussion 39 ## 40 ############################################################ 41 # 42 # We split the input into its individual characters and count 43 # each occurence by using a hash table. In the end, we check 44 # each letter whether it occurs an odd or even number of times. 45 # If any number occurs an even amount of times, we return false 46 # immediately. In the end, we can return true. 47 48 use v5.36; 49 50 odd_letters("weekly"); 51 odd_letters("perl"); 52 odd_letters("challenge"); 53 54 sub odd_letters($str) { 55 say "Input: \"$str\""; 56 my $map = {}; 57 foreach my $l (split //, $str) { 58 $map->{$l}++; 59 } 60 foreach my $l (keys %$map) { 61 if( $map->{$l} % 2 == 0) { 62 return say "Output: false"; 63 } 64 } 65 say "Output: true"; 66 }