Peter’s blog ✴ Week 273 ✴ 10 June 2024

THE WEEKLY CHALLENGE
All about characters

The Perl Camel

Task 1

Percentage of character

You are given a string, $str and a character $char. Write a script to return the percentage, nearest whole, of the given character in the given string.

Examples


Example 1
Input: $str = "perl", $char = "e"
Output: 25

Example 2
Input: $str = "java", $char = "a"
Output: 50

Example 3
Input: $str = "python", $char = "m"
Output: 0

Example 4
Input: $str = "ada", $char = "a"
Output: 67

Example 5
Input: $str = "ballerina", $char = "l"
Output: 22

Example 6
Input: $str = "analitik", $char = "k"
Output: 13

Analysis

What's needed is a fraction. The denominator is just length($str) and the numerator can be found by doing

$chars = $str;
$chars =~ s|[^$char]+||g;
whereupon length($chars) is the desired number.

All that remains is to divide one by the other, add 0.5 (to get the nearest percentage) and discard the fractional part.

I had hoped to be able to count the the number of $char by using

$count = ($str =~ y|$char|$char|)

but unfortunately that doesn't work because Perl doesn't evaluate $char in a transliteration: it treats '$char' as a literal string and counts the number of '$', 'c', 'h', 'a' and 'r'.

Perl Weekly’s review

from Perl Weekly issue 673

Perl pure regex implementation to deal with both tasks. Don't forget to try DIY tool.

Try it 

Try running the script with any input:



example: abracadabra is a magic spell



example: a

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-06-10
use utf8;     # Week 273 - task 1 - Percentage of character
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

percentage_of_character('the cat sat on the mat', 'a');
percentage_of_character('percentage of character', 'g');
percentage_of_character('the weekly challenge', 'z');
percentage_of_character('zzzzzzzzzzzzzzzzzz', 'z');

sub percentage_of_character {
    
    my ($str, $char, $chars);
    
    # remove $char from $str
    ($str, $char) = @_;
    $chars = $str;
    $chars =~ s|[^$char]+||g;
    
    say qq[\nInput:  \$str = '$str', \$char = '$char'];
    say qq[Output: ] . int(length($chars) / length($str) * 100 + 0.5);
}

7 lines of code

Output from script


Input:  $str = 'the cat sat on the mat', $char = 'a'
Output: 14

Input:  $str = 'percentage of character', $char = 'g'
Output: 4

Input:  $str = 'the weekly challenge', $char = 'z'
Output: 0

Input:  $str = 'zzzzzzzzzzzzzzzzzz', $char = 'z'
Output: 100

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain