summaryrefslogtreecommitdiff
path: root/_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html
diff options
context:
space:
mode:
authorPatrick Spek <p.spek@tyil.nl>2018-10-23 07:50:43 +0200
committerPatrick Spek <p.spek@tyil.nl>2018-10-23 07:50:43 +0200
commit9687d86e8e81bce5b01e96172405ac585a939e64 (patch)
tree68d8ae378207fab51091b1d32e150711aad60eca /_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html
parent1e2320f4ecb42430e54e42e1981cb284a6d6405f (diff)
Improve the count-substring solution in Perl 6
Diffstat (limited to '_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html')
-rw-r--r--_posts/2018-10-11-hackerrank-solutions-python3-and-perl6-part-2.html19
1 files 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.
<div class="language-defender">
<div class="language-code">
-{% 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) {
<div class="language-commentary">
{% 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 %}
</div>