From 9687d86e8e81bce5b01e96172405ac585a939e64 Mon Sep 17 00:00:00 2001 From: Patrick Spek Date: Tue, 23 Oct 2018 07:50:43 +0200 Subject: Improve the count-substring solution in Perl 6 --- ...hackerrank-solutions-python3-and-perl6-part-2.html | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html b/_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html index 26df2cb..92f4dc0 100644 --- a/_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html +++ b/_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html @@ -257,15 +257,9 @@ read, in my opinion.
-{% highlight perl6 tio=https://tio.run/##K0gtyjH7/7@4NEkhOb80r0QXyCouKcrMS1fQUIEwdBRUgIK6EI6mQjWXAhDkViqogDUo2CoYWHOBxdLyixTioJr0kjMSi4qhikEAolpbWyEzTQGmBmKXhko8ihUQrZoKqYXIotZgk2ohNkEMs@aq/Y/maA0VLU8/vfTUEqCJUJamXnFi5X9HJ2cXIOQCYgA %} +{% highlight perl6 tio=https://tio.run/##K0gtyjH7/7@4NEkhOb80r0QXyCouKcrMS1fQUIEwdBRUgIK6EI6mQjUXZ2pOam6xAlRaoa5OIdcqv0wfSZU@V@1/NOM0VLQ8/fTSU0uAxkFZmnrFiZX/HZ2cXYCQC4gB %} sub count-substring ($string, $sub-string) { - my $count = 0; - - for ^$string.chars { - $count++ if $string.substr($_, $sub-string.chars) eq $sub-string; - } - - $count; + elems $string ~~ m:overlap/$sub-string/ } {% endhighlight %} @@ -273,11 +267,10 @@ sub count-substring ($string, $sub-string) {
{% markdown %} -The Perl 6 solution has no special gimmicks compared to the Python version, it -also loops through the _string_ and looks for a match on the _sub\_string_ on -each location. One of the differences you can see is that I use `.chars` as a -method on the strings. This returns the number of characters found in a string, -and is actually aware of Unicode graphemes, unlike Python's `len` function. +The Perl 6 version makes use of some regex magic, and the `elems` subroutine. +`elems` returns the number of elements in a list, which in this case would be +the number of matches found by the regex. The `m:ov//` makes a regex to +*m*atch, with *ov*erlapping strings. {% endmarkdown %}
-- cgit v1.1