I’ve been doing the Weekly
Challenges. The
latest
involved poking through strings. (Note that this ends today.)
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 given
character in the given string.
Two parts to this, then: counting the matching characters, and doing
the calculation. Some languages (Ruby, Python, Crystal, Rust) will
just give you a count of the matching characters as a function of a
string; others allow a filter and count. And in Perl (and Lua) you
have to do it the hard way.
use integer;
sub percentageofcharacter($a, $c) {
my $d = length($a);
my $n = 0;
while ($a =~ /$c/g) {
$n++;
}
$n *= 100;
return ($n + $d / 2) / $d;
}
Most languages have integer variables these days; only JavaScript
forces me to use floating point. (I could use BigInts but it would be
a pain.)
function percentageofcharacter(a, c) {
const d = a.length;
const n = 100 * a.split("").filter(n => n == c).length;
return Math.floor(n / d + 0.5);
}
Task 2: B After A
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
.
In the simple regexp form, this would be matching /^[^b]*b[^a]*$/
.
But I tried doing without instead. Kotlin:
fun baftera(a: String): Boolean {
val firstb = a.indexOf('b')
val lasta = a.lastIndexOf('a')
if (firstb == -1) {
return false
}
if (lasta == -1) {
return true
}
return lasta < firstb
}
Lua and PostScript don't have a "find last", but one can reverse the
string, find first, and then do maths to get the index value.
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.