How to resolve the algorithm Jewels and stones step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Jewels and stones step by step in the Perl programming language
Table of Contents
Problem Statement
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.
Note that: So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Jewels and stones step by step in the Perl programming language
Source code in the perl programming language
sub count_jewels {
my( $j, $s ) = @_;
my($c,%S);
$S{$_}++ for split //, $s;
$c += $S{$_} for split //, $j;
return "$c\n";
}
print count_jewels 'aA' , 'aAAbbbb';
print count_jewels 'z' , 'ZZ';
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Jewels_and_Stones#Perl
use warnings;
sub count_jewels { scalar( () = $_[0] =~ /[ $_[1] ]/gx ) } # stones, jewels
print "$_ = ", count_jewels( split ), "\n" for split /\n/, <<END;
aAAbbbb aA
aAAbbbb abc
ZZ z
END
You may also check:How to resolve the algorithm Averages/Median step by step in the Clojure programming language
You may also check:How to resolve the algorithm Copy a string step by step in the PHP programming language
You may also check:How to resolve the algorithm P-value correction step by step in the Java programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the VBScript programming language
You may also check:How to resolve the algorithm Last letter-first letter step by step in the Kotlin programming language