How to resolve the algorithm Jewels and stones step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Jewels and stones step by step in the Raku 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 Raku programming language

Source code in the raku programming language

sub count-jewels ( Str $j, Str $s --> Int ) {
    my %counts_of_all = $s.comb.Bag;
    my @jewel_list    = $j.comb.unique;

    return %counts_of_all ∩ @jewel_list.Bag ?? %counts_of_all{ @jewel_list }.sum !! 0;
}

say count-jewels 'aA' , 'aAAbbbb';
say count-jewels 'z'  , 'ZZ';


  

You may also check:How to resolve the algorithm GUI/Maximum window dimensions step by step in the Axe programming language
You may also check:How to resolve the algorithm Chaos game step by step in the Julia programming language
You may also check:How to resolve the algorithm Honeycombs step by step in the Scala programming language
You may also check:How to resolve the algorithm Lah numbers step by step in the ALGOL W programming language
You may also check:How to resolve the algorithm Rosetta Code/Find unimplemented tasks step by step in the Run BASIC programming language