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

Published on 12 May 2024 09:40 PM

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

Source code in the prolog programming language

:- system:set_prolog_flag(double_quotes,codes) .

count_jewels(STONEs0,JEWELs0,COUNT)
:-
findall(X,(member(X,JEWELs0),member(X,STONEs0)),ALLs) ,
length(ALLs,COUNT)
.


count_jewels(Stones, Jewels, N):-
    string_codes(Stones, Scodes),
    string_codes(Jewels, Jcodes),
    msort(Scodes, SScodes),
    sort(Jcodes, SJcodes),
    count_jewels(SScodes, SJcodes, N, 0).

count_jewels([], _, N, N):-!.
count_jewels(_, [], N, N):-!.
count_jewels([C|Stones], [C|Jewels], N, R):-
    !,
    R1 is R + 1,
    count_jewels(Stones, [C|Jewels], N, R1).
count_jewels([S|Stones], [J|Jewels], N, R):-
    J < S,
    !,
    count_jewels([S|Stones], Jewels, N, R).
count_jewels([_|Stones], Jewels, N, R):-
    count_jewels(Stones, Jewels, N, R).


  

You may also check:How to resolve the algorithm Unbias a random generator step by step in the GAP programming language
You may also check:How to resolve the algorithm Reduced row echelon form step by step in the Ada programming language
You may also check:How to resolve the algorithm Intersecting number wheels step by step in the Raku programming language
You may also check:How to resolve the algorithm Truncate a file step by step in the Java programming language
You may also check:How to resolve the algorithm Nested templated data step by step in the Crystal programming language