The weekly challenge 273 - Task 1: Percentage of Character
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-273/#TASK1 3 # 4 # Task 1: Percentage of Character 5 # =============================== 6 # 7 # You are given a string, $str and a character $char. 8 # 9 # Write a script to return the percentage, nearest whole, of given character in 10 # the given string. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "perl", $char = "e" 15 ## Output: 25 16 # 17 ## Example 2 18 ## 19 ## Input: $str = "java", $char = "a" 20 ## Output: 50 21 # 22 ## Example 3 23 ## 24 ## Input: $str = "python", $char = "m" 25 ## Output: 0 26 # 27 ## Example 4 28 ## 29 ## Input: $str = "ada", $char = "a" 30 ## Output: 67 31 # 32 ## Example 5 33 ## 34 ## Input: $str = "ballerina", $char = "l" 35 ## Output: 22 36 # 37 ## Example 6 38 ## 39 ## Input: $str = "analitik", $char = "k" 40 ## Output: 13 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # We split $str into its characters and count both the overall 49 # sum and the sum of the characters that match $char. We calculate 50 # the percentage, add 0.5 and convert to an integer. This way, we 51 # obtain the nearest whole percentage. 52 53 use strict; 54 use warnings; 55 56 percentage_of_char("perl", "e"); 57 percentage_of_char("java", "a"); 58 percentage_of_char("python", "m"); 59 percentage_of_char("ada", "a"); 60 percentage_of_char("ballerina", "l"); 61 percentage_of_char("analitik", "k"); 62 63 sub percentage_of_char { 64 my ($str, $char) = @_; 65 print "Input: '$str', '$char'\n"; 66 my $overall_char_count = 0; 67 my $this_char_count = 0; 68 foreach my $c (split //, $str) { 69 $overall_char_count++; 70 $this_char_count++ if $c eq $char; 71 } 72 my $percentage = int(100*$this_char_count/$overall_char_count + 0.5); 73 print "Output: $percentage\n"; 74 }