site.base_url }}/">The Bear's Den -->

The Bear's Den

Enter at your own risk

Looking After The Percentage

Task 1: Percentage of Character

Submitted by: Mohammad Sajid Anwar


You are given a string, $str and a character $char.

Write a script to return the percentage, nearest whole, of given character in the given string.

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

Solution

We are asked for the percentage of a character within a string, but with almost no extra effort this can be generalized to the percentage of a substring within a string. All we have to do is take the length of the substring into account.

The number of the substring’s occurrences can be found with a global match in list context. Meta characters have to be quoted, though.

use strict;
use warnings;
use experimental 'signatures';

sub pct_sub ($sub, $str) {
    return int .5 + 100 * (() = /\Q$sub/g) * length($sub) / length for $str;
}

See the full solution to task 1.

Task 2: B After A

Submitted by: Mohammad Sajid Anwar


You are given a string, $str.

Write a script to return true if there is at least one b, and no a appears after the first b.

Example 1

Input: $str = "aabb"
Output: true

Example 2

Input: $str = "abab"
Output: false

Example 3

Input: $str = "aaa"
Output: false

Example 4

Input: $str = "bbb"
Output: true

Solution

To find the first b in the string, we match as many non-b characters as possible from the start of the string and we never give back any. This must be followed by a b, followed by any number of non-a characters, again never giving back any, up to the end of the string.

The resulting regex is /^[^b]*+b[^a]*+$/, that never will backtrack. Either it matches in one pass or it fails instantly.

use strict;
use warnings;

sub b_after_a {
    shift =~ /^[^b]*+b[^a]*+$/;
}

See the full solution to task 2.


If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.