Jewels and stones: Difference between revisions

From Rosetta Code
Content added Content deleted
(add bqn)
m (syntax highlighting fixup automation)
Line 29: Line 29:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F count_jewels(s, j)
<syntaxhighlight lang="11l">F count_jewels(s, j)
R sum(s.map(x -> Int(x C @j)))
R sum(s.map(x -> Int(x C @j)))


print(count_jewels(‘aAAbbbb’, ‘aA’))
print(count_jewels(‘aAAbbbb’, ‘aA’))
print(count_jewels(‘ZZ’, ‘z’))</lang>
print(count_jewels(‘ZZ’, ‘z’))</syntaxhighlight>


{{out}}
{{out}}
Line 43: Line 43:
=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==


<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Count jewels.
;;; Count jewels.
Line 105: Line 105:
;;; Next free page of memory is used for the jewel array
;;; Next free page of memory is used for the jewel array
jpage: equ $/256+1
jpage: equ $/256+1
jarr: equ jpage*256</lang>
jarr: equ jpage*256</syntaxhighlight>


{{out}}
{{out}}
Line 114: Line 114:
=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==


<lang asm> cpu 8086
<syntaxhighlight lang="asm"> cpu 8086
bits 16
bits 16
org 100h
org 100h
Line 167: Line 167:
num: db '$'
num: db '$'
stones: db 'aAAbbbb',0 ; Example from the task
stones: db 'aAAbbbb',0 ; Example from the task
jewels: db 'aA',0</lang>
jewels: db 'aA',0</syntaxhighlight>


{{out}}
{{out}}
Line 174: Line 174:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Jewels_And_Stones is
procedure Jewels_And_Stones is
Line 205: Line 205:
Show ("aAAbbbb", "aA");
Show ("aAAbbbb", "aA");
Show ("ZZ", "z");
Show ("ZZ", "z");
end Jewels_And_Stones;</lang>
end Jewels_And_Stones;</syntaxhighlight>


{{out}}
{{out}}
Line 212: Line 212:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# procedure that counts the number of times the letters in jewels occur in stones #
# procedure that counts the number of times the letters in jewels occur in stones #
PROC count jewels = ( STRING stones, jewels )INT:
PROC count jewels = ( STRING stones, jewels )INT:
Line 248: Line 248:
print( ( count jewels( "ZZ", "z" ), newline ) )
print( ( count jewels( "ZZ", "z" ), newline ) )


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre> +3
<pre> +3
Line 258: Line 258:
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}


<lang apl>jewels ← +/∊⍨</lang>
<syntaxhighlight lang="apl">jewels ← +/∊⍨</syntaxhighlight>


{{out}}
{{out}}
Line 268: Line 268:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
===Functional===
===Functional===
<lang applescript>-- jewelCount :: String -> String -> Int
<syntaxhighlight lang="applescript">-- jewelCount :: String -> String -> Int
on jewelCount(jewels, stones)
on jewelCount(jewels, stones)
set js to chars(jewels)
set js to chars(jewels)
Line 390: Line 390:
set my text item delimiters to dlm
set my text item delimiters to dlm
str
str
end unlines</lang>
end unlines</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 397: Line 397:
===Idiomatic===
===Idiomatic===


<lang applescript>on jewelsAndStones(stones, jewels)
<syntaxhighlight lang="applescript">on jewelsAndStones(stones, jewels)
set counter to 0
set counter to 0
considering case
considering case
Line 408: Line 408:
end jewelsAndStones
end jewelsAndStones


jewelsAndStones("aAAbBbb", "aAb")</lang>
jewelsAndStones("aAAbBbb", "aAb")</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>6</lang>
<syntaxhighlight lang="applescript">6</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>count: function [jewels,stones][
<syntaxhighlight lang="rebol">count: function [jewels,stones][
size select split stones => [in? & jewels]
size select split stones => [in? & jewels]
]
]


print count "aA" "aAAbbbb"</lang>
print count "aA" "aAAbbbb"</syntaxhighlight>


{{out}}
{{out}}
Line 425: Line 425:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>JewelsandStones(ss, jj){
<syntaxhighlight lang="autohotkey">JewelsandStones(ss, jj){
for each, jewel in StrSplit(jj)
for each, jewel in StrSplit(jj)
for each, stone in StrSplit(ss)
for each, stone in StrSplit(ss)
Line 431: Line 431:
num++
num++
return num
return num
}</lang>
}</syntaxhighlight>
Example:<lang AutoHotkey>MsgBox % JewelsandStones("aAAbbbbz", "aAZ")
Example:<syntaxhighlight lang="autohotkey">MsgBox % JewelsandStones("aAAbbbbz", "aAZ")
return</lang>
return</syntaxhighlight>
Outputs:<pre>3</pre>
Outputs:<pre>3</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK># syntax: GAWK -f JEWELS_AND_STONES.AWK
<syntaxhighlight lang="awk"># syntax: GAWK -f JEWELS_AND_STONES.AWK
BEGIN {
BEGIN {
printf("%d\n",count("aAAbbbb","aA"))
printf("%d\n",count("aAAbbbb","aA"))
Line 451: Line 451:
return(total)
return(total)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>3
<pre>3
Line 458: Line 458:
=={{header|BASIC}}==
=={{header|BASIC}}==


<lang basic>10 READ N%
<syntaxhighlight lang="basic">10 READ N%
20 FOR A%=1 TO N%
20 FOR A%=1 TO N%
30 READ J$,S$
30 READ J$,S$
Line 477: Line 477:
210 DATA "aA","aAAbbbb"
210 DATA "aA","aAAbbbb"
220 DATA "z","ZZZZ"
220 DATA "z","ZZZZ"
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 485: Line 485:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
function contar_joyas(piedras, joyas)
function contar_joyas(piedras, joyas)
cont = 0
cont = 0
Line 499: Line 499:
print contar_joyas("ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
print contar_joyas("ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
print contar_joyas("AB", "")
print contar_joyas("AB", "")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 506: Line 506:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let jewels(j, s) = valof
let jewels(j, s) = valof
Line 525: Line 525:
$( show("aA", "aAAbbbb")
$( show("aA", "aAAbbbb")
show("z", "ZZ")
show("z", "ZZ")
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>"aA" in "aAAbbbb": 3
<pre>"aA" in "aAAbbbb": 3
Line 533: Line 533:
Similar in nature to APL, mostly due to how trivial the problem is in an array language.
Similar in nature to APL, mostly due to how trivial the problem is in an array language.


<lang bqn>Jewels←+´∊˜</lang>
<syntaxhighlight lang="bqn">Jewels←+´∊˜</syntaxhighlight>
<lang> "aA" Jewels "aAAbbbb"
<syntaxhighlight lang="text"> "aA" Jewels "aAAbbbb"
3</lang>
3</syntaxhighlight>
=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang Bracmat> ( f
<syntaxhighlight lang="bracmat"> ( f
= stones jewels N
= stones jewels N
. !arg:(?stones.?jewels)
. !arg:(?stones.?jewels)
Line 556: Line 556:
)
)
& f$(aAAbbbb.aA)
& f$(aAAbbbb.aA)
</syntaxhighlight>
</lang>
'''Output'''
'''Output'''
<pre>3</pre>
<pre>3</pre>
Line 562: Line 562:
=={{header|C}}==
=={{header|C}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>


Line 575: Line 575:
printf("%d\n", count_jewels("ZZ", "z"));
printf("%d\n", count_jewels("ZZ", "z"));
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 584: Line 584:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 598: Line 598:
return stones.Count(bag.Contains);
return stones.Count(bag.Contains);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 607: Line 607:
=={{header|C++}}==
=={{header|C++}}==
{{trans|D}}
{{trans|D}}
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>


Line 627: Line 627:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 633: Line 633:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>count_jewels = proc (jewels, stones: string) returns (int)
<syntaxhighlight lang="clu">count_jewels = proc (jewels, stones: string) returns (int)
is_jewel: array[bool] := array[bool]$fill(0, 256, false)
is_jewel: array[bool] := array[bool]$fill(0, 256, false)
for c: char in string$chars(jewels) do
for c: char in string$chars(jewels) do
Line 655: Line 655:
start_up = proc ()
start_up = proc ()
show("aA", "aAAbbbb")
show("aA", "aAAbbbb")
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>"aA" in "aAAbbbb": 3</pre>
<pre>"aA" in "aAAbbbb": 3</pre>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


sub count_jewels(stones: [uint8], jewels: [uint8]): (count: uint16) is
sub count_jewels(stones: [uint8], jewels: [uint8]): (count: uint16) is
Line 688: Line 688:


print_and_count("aAAbbbb", "aA");
print_and_count("aAAbbbb", "aA");
print_and_count("ZZ", "z");</lang>
print_and_count("ZZ", "z");</syntaxhighlight>


{{out}}
{{out}}
Line 696: Line 696:


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby>stones, jewels = "aAAbbbb", "aA"
<syntaxhighlight lang="ruby">stones, jewels = "aAAbbbb", "aA"
stones.count(jewels) # => 3
stones.count(jewels) # => 3


Line 705: Line 705:


# This works as intended though:
# This works as intended though:
stones.count { |c| jewels.chars.includes?(c) } # => 2</lang>
stones.count { |c| jewels.chars.includes?(c) } # => 2</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang d>import std.algorithm;
<syntaxhighlight lang="d">import std.algorithm;
import std.stdio;
import std.stdio;


Line 725: Line 725:
countJewels("aAAbbbb", "aA").writeln;
countJewels("aAAbbbb", "aA").writeln;
countJewels("ZZ", "z").writeln;
countJewels("ZZ", "z").writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 731: Line 731:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>proc nonrec count_jewels(*char jewels, stones) word:
<syntaxhighlight lang="draco">proc nonrec count_jewels(*char jewels, stones) word:
[256] bool jewel;
[256] bool jewel;
word count;
word count;
Line 758: Line 758:
show("aA", "aAAbbbb");
show("aA", "aAAbbbb");
show("z", "ZZ")
show("z", "ZZ")
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>'aA' in 'aAAbbbb': 3
<pre>'aA' in 'aAAbbbb': 3
Line 767: Line 767:
{{trans|Swift}}
{{trans|Swift}}


<lang dyalect>func countJewels(stones, jewels) {
<syntaxhighlight lang="dyalect">func countJewels(stones, jewels) {
stones.Iterate().Map(x => jewels.Contains(x) ? 1 : 0).Reduce((x,y) => x + y, 0)
stones.Iterate().Map(x => jewels.Contains(x) ? 1 : 0).Reduce((x,y) => x + y, 0)
}
}
print(countJewels("aAAbbbb", "aA"))
print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))</lang>
print(countJewels("ZZ", "z"))</syntaxhighlight>


{{out}}
{{out}}
Line 780: Line 780:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let fN jewels stones=stones|>Seq.filter(fun n->Seq.contains n jewels)|>Seq.length
let fN jewels stones=stones|>Seq.filter(fun n->Seq.contains n jewels)|>Seq.length
printfn "%d" (fN "aA" "aAAbbbb")
printfn "%d" (fN "aA" "aAAbbbb")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 790: Line 790:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: kernel prettyprint sequences ;
<syntaxhighlight lang="factor">USING: kernel prettyprint sequences ;


: count-jewels ( stones jewels -- n ) [ member? ] curry count ;
: count-jewels ( stones jewels -- n ) [ member? ] curry count ;


"aAAbbbb" "aA"
"aAAbbbb" "aA"
"ZZ" "z" [ count-jewels . ] 2bi@</lang>
"ZZ" "z" [ count-jewels . ] 2bi@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 803: Line 803:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function number_of(object jewels, object stones) -- why limit ourselves to strings?
function number_of(object jewels, object stones) -- why limit ourselves to strings?
integer ct = 0
integer ct = 0
Line 815: Line 815:
? number_of("z","ZZ")
? number_of("z","ZZ")
? number_of({1,"Boo",3},{1,2,3,'A',"Boo",3}) -- might as well send a list of things to find, not just one!
? number_of({1,"Boo",3},{1,2,3,'A',"Boo",3}) -- might as well send a list of things to find, not just one!
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 824: Line 824:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
function contar_joyas(piedras as string, joyas as string) as integer
function contar_joyas(piedras as string, joyas as string) as integer
dim as integer bc, cont: cont = 0
dim as integer bc, cont: cont = 0
Line 839: Line 839:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
"ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
print contar_joyas("AB", "")
print contar_joyas("AB", "")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 854: Line 854:


'''Outer loop stones, index into jewels:'''
'''Outer loop stones, index into jewels:'''
<lang go>package main
<syntaxhighlight lang="go">package main
import (
import (
Line 872: Line 872:
func main() {
func main() {
fmt.Println(js("aAAbbbb", "aA"))
fmt.Println(js("aAAbbbb", "aA"))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


'''Outer loop jewels, count stones:'''
'''Outer loop jewels, count stones:'''
<lang go>func js(stones, jewels string) (n int) {
<syntaxhighlight lang="go">func js(stones, jewels string) (n int) {
for _, b := range []byte(jewels) {
for _, b := range []byte(jewels) {
n += strings.Count(stones, string(b))
n += strings.Count(stones, string(b))
}
}
return
return
}</lang>
}</syntaxhighlight>


'''Construct jewel set, then loop over stones:'''
'''Construct jewel set, then loop over stones:'''
<lang go>func js(stones, jewels string) (n int) {
<syntaxhighlight lang="go">func js(stones, jewels string) (n int) {
var jSet ['z' + 1]int
var jSet ['z' + 1]int
for _, b := range []byte(jewels) {
for _, b := range []byte(jewels) {
Line 894: Line 894:
}
}
return
return
}</lang>
}</syntaxhighlight>


'''Construct stone multiset, then loop over jewels:'''
'''Construct stone multiset, then loop over jewels:'''
<lang go>func js(stones, jewels string) (n int) {
<syntaxhighlight lang="go">func js(stones, jewels string) (n int) {
var sset ['z' + 1]int
var sset ['z' + 1]int
for _, b := range []byte(stones) {
for _, b := range []byte(stones) {
Line 906: Line 906:
}
}
return
return
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>jewelCount
<syntaxhighlight lang="haskell">jewelCount
:: Eq a
:: Eq a
=> [a] -> [a] -> Int
=> [a] -> [a] -> Int
Line 921: Line 921:
main :: IO ()
main :: IO ()
main = mapM_ print $ uncurry jewelCount <$> [("aA", "aAAbbbb"), ("z", "ZZ")]
main = mapM_ print $ uncurry jewelCount <$> [("aA", "aAAbbbb"), ("z", "ZZ")]
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 928: Line 928:
Or in terms of filter rather than foldr
Or in terms of filter rather than foldr


<lang haskell>jewelCount
<syntaxhighlight lang="haskell">jewelCount
:: Eq a
:: Eq a
=> [a] -> [a] -> Int
=> [a] -> [a] -> Int
Line 937: Line 937:
main = do
main = do
print $ jewelCount "aA" "aAAbbbb"
print $ jewelCount "aA" "aAAbbbb"
print $ jewelCount "z" "ZZ"</lang>
print $ jewelCount "z" "ZZ"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 943: Line 943:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
NB. jewels sums a raveled equality table
NB. jewels sums a raveled equality table
NB. use: x jewels y x are the stones, y are the jewels.
NB. use: x jewels y x are the stones, y are the jewels.
Line 957: Line 957:
0
0
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.HashSet;
<syntaxhighlight lang="java">import java.util.HashSet;
import java.util.Set;
import java.util.Set;


Line 984: Line 984:
System.out.println(countJewels("ZZ", "z"));
System.out.println(countJewels("ZZ", "z"));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 990: Line 990:


=={{header|Javascript}}==
=={{header|Javascript}}==
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {


// jewelCount :: String -> String -> Int
// jewelCount :: String -> String -> Int
Line 1,005: Line 1,005:
]
]
.map(x => jewelCount(...x))
.map(x => jewelCount(...x))
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[3, 0]</pre>
<pre>[3, 0]</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>$ jq -n --arg stones aAAbbbb --arg jewels aA '
<syntaxhighlight lang="jq">$ jq -n --arg stones aAAbbbb --arg jewels aA '
[$stones|split("") as $s|$jewels|split("") as $j|$s[]|
[$stones|split("") as $s|$jewels|split("") as $j|$s[]|
select(. as $c|$j|contains([$c]))]|length'</lang>
select(. as $c|$j|contains([$c]))]|length'</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,020: Line 1,020:


'''Module''':
'''Module''':
<lang julia>module Jewels
<syntaxhighlight lang="julia">module Jewels


count(s, j) = Base.count(x ∈ j for x in s)
count(s, j) = Base.count(x ∈ j for x in s)


end # module Jewels</lang>
end # module Jewels</syntaxhighlight>


'''Main''':
'''Main''':
<lang julia>@show Jewels.count("aAAbbbb", "aA")
<syntaxhighlight lang="julia">@show Jewels.count("aAAbbbb", "aA")
@show Jewels.count("ZZ", "z")</lang>
@show Jewels.count("ZZ", "z")</syntaxhighlight>


{{out}}
{{out}}
Line 1,035: Line 1,035:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// Version 1.2.40
<syntaxhighlight lang="scala">// Version 1.2.40


fun countJewels(s: String, j: String) = s.count { it in j }
fun countJewels(s: String, j: String) = s.count { it in j }
Line 1,042: Line 1,042:
println(countJewels("aAAbbbb", "aA"))
println(countJewels("aAAbbbb", "aA"))
println(countJewels("ZZ", "z"))
println(countJewels("ZZ", "z"))
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 1,051: Line 1,051:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def countjewels
{def countjewels
{def countjewels.r
{def countjewels.r
Line 1,068: Line 1,068:
{countjewels aAAbbbb aA} -> 3
{countjewels aAAbbbb aA} -> 3
{countjewels ZZ z} -> 0
{countjewels ZZ z} -> 0
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C}}
{{trans|C}}
<lang lua>function count_jewels(s, j)
<syntaxhighlight lang="lua">function count_jewels(s, j)
local count = 0
local count = 0
for i=1,#s do
for i=1,#s do
Line 1,084: Line 1,084:


print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("ZZ", "z"))</lang>
print(count_jewels("ZZ", "z"))</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,090: Line 1,090:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>count_jewel := proc(stones, jewels)
<syntaxhighlight lang="maple">count_jewel := proc(stones, jewels)
local count, j, letter:
local count, j, letter:
j := convert(jewels,set):
j := convert(jewels,set):
Line 1,101: Line 1,101:
return count:
return count:
end proc:
end proc:
count_jewel("aAAbbbb", "aA")</lang>
count_jewel("aAAbbbb", "aA")</syntaxhighlight>
{{Out|Output}}
{{Out|Output}}
<pre>3</pre>
<pre>3</pre>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>JewelsStones[j_String, s_String] := Count[MemberQ[Characters[j], #] & /@ Characters[s], True]
<syntaxhighlight lang="mathematica">JewelsStones[j_String, s_String] := Count[MemberQ[Characters[j], #] & /@ Characters[s], True]
JewelsStones["aA", "aAAbbbb"]
JewelsStones["aA", "aAAbbbb"]
JewelsStones["ZZ", "z"]</lang>
JewelsStones["ZZ", "z"]</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,114: Line 1,114:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function s = count_jewels(stones,jewels)
function s = count_jewels(stones,jewels)
s=0;
s=0;
Line 1,124: Line 1,124:
%!test
%!test
%! assert(count_jewels('ZZ','z'),0)
%! assert(count_jewels('ZZ','z'),0)
</syntaxhighlight>
</lang>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>(('' '' '') => spread if) :if?
<syntaxhighlight lang="min">(('' '' '') => spread if) :if?


((1 0 if?) concat map sum) :count
((1 0 if?) concat map sum) :count
Line 1,137: Line 1,137:


"aAAbbbb" "aA" count-jewels puts!
"aAAbbbb" "aA" count-jewels puts!
"ZZ" "z" count-jewels puts!</lang>
"ZZ" "z" count-jewels puts!</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,145: Line 1,145:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Jewels;
<syntaxhighlight lang="modula2">MODULE Jewels;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,180: Line 1,180:


ReadChar
ReadChar
END Jewels.</lang>
END Jewels.</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,186: Line 1,186:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import sequtils
<syntaxhighlight lang="nim">import sequtils


func countJewels(stones, jewels: string): Natural =
func countJewels(stones, jewels: string): Natural =
Line 1,192: Line 1,192:


echo countJewels("aAAbbbb", "aA")
echo countJewels("aAAbbbb", "aA")
echo countJewels("ZZ", "z")</lang>
echo countJewels("ZZ", "z")</syntaxhighlight>


{{out}}
{{out}}
Line 1,200: Line 1,200:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang Objeck>use Collection.Generic;
<syntaxhighlight lang="objeck">use Collection.Generic;


class JewelsStones {
class JewelsStones {
Line 1,224: Line 1,224:
return count;
return count;
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,233: Line 1,233:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub count_jewels {
<syntaxhighlight lang="perl">sub count_jewels {
my( $j, $s ) = @_;
my( $j, $s ) = @_;
my($c,%S);
my($c,%S);
Line 1,243: Line 1,243:


print count_jewels 'aA' , 'aAAbbbb';
print count_jewels 'aA' , 'aAAbbbb';
print count_jewels 'z' , 'ZZ';</lang>
print count_jewels 'z' , 'ZZ';</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
0</pre>
0</pre>
===Alternate using regex===
===Alternate using regex===
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl


use strict; # https://rosettacode.org/wiki/Jewels_and_Stones#Perl
use strict; # https://rosettacode.org/wiki/Jewels_and_Stones#Perl
Line 1,259: Line 1,259:
aAAbbbb abc
aAAbbbb abc
ZZ z
ZZ z
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,268: Line 1,268:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">stones</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jewels</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">stones</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jewels</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 1,278: Line 1,278:
<span style="color: #0000FF;">?</span><span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"aAAbbbb"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"aA"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"aAAbbbb"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"aA"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ZZ"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"z"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">count_jewels</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ZZ"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"z"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,288: Line 1,288:
===List comprehension===
===List comprehension===


<lang Picat>jewels_and_stones1(Jewels,Stones) = sum([1 : S in Stones, J in Jewels, S == J]).</lang>
<syntaxhighlight lang="picat">jewels_and_stones1(Jewels,Stones) = sum([1 : S in Stones, J in Jewels, S == J]).</syntaxhighlight>


===Recursion===
===Recursion===
<lang Picat>jewels_and_stones2(Jewels,Stones) = N =>
<syntaxhighlight lang="picat">jewels_and_stones2(Jewels,Stones) = N =>
jewels_and_stones2(Jewels,Stones,0,N).
jewels_and_stones2(Jewels,Stones,0,N).


Line 1,307: Line 1,307:
N1 = N0
N1 = N0
),
),
jewels_and_stones2_(J,Stones,N1,N).</lang>
jewels_and_stones2_(J,Stones,N1,N).</syntaxhighlight>


===Foreach loop===
===Foreach loop===
<lang Picat>jewels_and_stones3(Jewels,Stones) = N =>
<syntaxhighlight lang="picat">jewels_and_stones3(Jewels,Stones) = N =>
N = 0,
N = 0,
foreach(J in Jewels, S in Stones)
foreach(J in Jewels, S in Stones)
Line 1,316: Line 1,316:
N := N + 1
N := N + 1
end
end
end.</lang>
end.</syntaxhighlight>


===Test===
===Test===
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
Tests = [["aA","aAAbbbb"],
Tests = [["aA","aAAbbbb"],
["z","ZZ"]
["z","ZZ"]
Line 1,331: Line 1,331:
nl
nl
end,
end,
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 1,347: Line 1,347:
===Benchmark===
===Benchmark===
For a larger test we can see the differences between the three approaches. Here are 100 000 000 random stones and (atmost) 15 jewels (we remove any duplicate jewel).
For a larger test we can see the differences between the three approaches. Here are 100 000 000 random stones and (atmost) 15 jewels (we remove any duplicate jewel).
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
Alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
Alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
Len = Alpha.len,
Len = Alpha.len,
Line 1,361: Line 1,361:
time(println(js2=jewels_and_stones2(Jewels,Stones))),
time(println(js2=jewels_and_stones2(Jewels,Stones))),
time(println(js3=jewels_and_stones3(Jewels,Stones))),
time(println(js3=jewels_and_stones3(Jewels,Stones))),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 1,383: Line 1,383:


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang plm>100H:
<syntaxhighlight lang="plm">100H:


/* FIND JEWELS AMONG STONES */
/* FIND JEWELS AMONG STONES */
Line 1,458: Line 1,458:


CALL BDOS(0,0);
CALL BDOS(0,0);
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>'aA' IN 'aAAbbbb': 3
<pre>'aA' IN 'aAAbbbb': 3
Line 1,465: Line 1,465:
=={{header|Prolog}}==
=={{header|Prolog}}==


<lang prolog>
<syntaxhighlight lang="prolog">


:- system:set_prolog_flag(double_quotes,codes) .
:- system:set_prolog_flag(double_quotes,codes) .
Line 1,475: Line 1,475:
.
.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,496: Line 1,496:


{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>count_jewels(Stones, Jewels, N):-
<syntaxhighlight lang="prolog">count_jewels(Stones, Jewels, N):-
string_codes(Stones, Scodes),
string_codes(Stones, Scodes),
string_codes(Jewels, Jcodes),
string_codes(Jewels, Jcodes),
Line 1,514: Line 1,514:
count_jewels([S|Stones], Jewels, N, R).
count_jewels([S|Stones], Jewels, N, R).
count_jewels([_|Stones], Jewels, N, R):-
count_jewels([_|Stones], Jewels, N, R):-
count_jewels(Stones, Jewels, N, R).</lang>
count_jewels(Stones, Jewels, N, R).</syntaxhighlight>


{{out}}
{{out}}
Line 1,530: Line 1,530:


=={{header|Python}}==
=={{header|Python}}==
<lang python>def countJewels(s, j):
<syntaxhighlight lang="python">def countJewels(s, j):
return sum(x in j for x in s)
return sum(x in j for x in s)


print countJewels("aAAbbbb", "aA")
print countJewels("aAAbbbb", "aA")
print countJewels("ZZ", "z")</lang>
print countJewels("ZZ", "z")</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 1,540: Line 1,540:


===Python 3 Alternative===
===Python 3 Alternative===
<lang python>def countJewels(stones, jewels):
<syntaxhighlight lang="python">def countJewels(stones, jewels):
jewelset = set(jewels)
jewelset = set(jewels)
return sum(1 for stone in stones if stone in jewelset)
return sum(1 for stone in stones if stone in jewelset)


print(countJewels("aAAbbbb", "aA"))
print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))</lang>
print(countJewels("ZZ", "z"))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 1,551: Line 1,551:


=={{header|R}}==
=={{header|R}}==
<lang R>J_n_S <- function(stones ="aAAbbbb", jewels = "aA") {
<syntaxhighlight lang="r">J_n_S <- function(stones ="aAAbbbb", jewels = "aA") {
stones <- unlist(strsplit(stones, split = "")) # obtain a character vector
stones <- unlist(strsplit(stones, split = "")) # obtain a character vector
jewels <- unlist(strsplit(jewels, split = ""))
jewels <- unlist(strsplit(jewels, split = ""))
Line 1,560: Line 1,560:
print(J_n_S("ZZ", "z"))
print(J_n_S("ZZ", "z"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH"))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>> print(J_n_S("aAAbbbb", "aA"))
<pre>> print(J_n_S("aAAbbbb", "aA"))
Line 1,572: Line 1,572:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ 0 0 rot
<syntaxhighlight lang="quackery"> [ 0 0 rot
witheach [ bit | ]
witheach [ bit | ]
rot witheach
rot witheach
Line 1,579: Line 1,579:
drop ] is j&s ( $ $ --> n )
drop ] is j&s ( $ $ --> n )


$ "aAAbbbb" $ "aA" j&s echo</lang>
$ "aAAbbbb" $ "aA" j&s echo</syntaxhighlight>


{{out}}
{{out}}
Line 1,586: Line 1,586:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (jewels-and-stones stones jewels)
(define (jewels-and-stones stones jewels)
Line 1,594: Line 1,594:
(jewels-and-stones "aAAbbbb" "aA")
(jewels-and-stones "aAAbbbb" "aA")
(jewels-and-stones "ZZ" "z"))
(jewels-and-stones "ZZ" "z"))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,601: Line 1,601:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub count-jewels ( Str $j, Str $s --> Int ) {
<syntaxhighlight lang="raku" line>sub count-jewels ( Str $j, Str $s --> Int ) {
my %counts_of_all = $s.comb.Bag;
my %counts_of_all = $s.comb.Bag;
my @jewel_list = $j.comb.unique;
my @jewel_list = $j.comb.unique;
Line 1,609: Line 1,609:


say count-jewels 'aA' , 'aAAbbbb';
say count-jewels 'aA' , 'aAAbbbb';
say count-jewels 'z' , 'ZZ';</lang>
say count-jewels 'z' , 'ZZ';</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 1,615: Line 1,615:


=={{header|Red}}==
=={{header|Red}}==
<lang rebol>Red [
<syntaxhighlight lang="rebol">Red [
title: "Jewels and stones"
title: "Jewels and stones"
red-version: 0.6.4
red-version: 0.6.4
Line 1,642: Line 1,642:


print count-jewels "aAAbbbb" "aA"
print count-jewels "aAAbbbb" "aA"
print count-jewels "ZZ" "z"</lang>
print count-jewels "ZZ" "z"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,651: Line 1,651:
=={{header|REXX}}==
=={{header|REXX}}==
Programming note: &nbsp; a check is made so that only (Latin) letters are counted as a match.
Programming note: &nbsp; a check is made so that only (Latin) letters are counted as a match.
<lang rexx>/*REXX pgm counts how many letters (in the 1st string) are in common with the 2nd string*/
<syntaxhighlight lang="rexx">/*REXX pgm counts how many letters (in the 1st string) are in common with the 2nd string*/
say count('aAAbbbb', "aA")
say count('aAAbbbb', "aA")
say count('ZZ' , "z" )
say count('ZZ' , "z" )
Line 1,662: Line 1,662:
if datatype(x, 'M') then if pos(x, jewels)\==0 then #= # + 1
if datatype(x, 'M') then if pos(x, jewels)\==0 then #= # + 1
end /*j*/ /* [↑] if a letter and a match, bump #*/
end /*j*/ /* [↑] if a letter and a match, bump #*/
return # /*return the number of common letters. */</lang>
return # /*return the number of common letters. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>3
<pre>3
Line 1,668: Line 1,668:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring># Project Jewels and Stones
<syntaxhighlight lang="ring"># Project Jewels and Stones
jewels = "aA"
jewels = "aA"
Line 1,686: Line 1,686:
next
next
return num
return num
</syntaxhighlight>
</lang>
Output:
Output:
<pre>3
<pre>3
Line 1,692: Line 1,692:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>stones, jewels = "aAAbbbb", "aA"
<syntaxhighlight lang="ruby">stones, jewels = "aAAbbbb", "aA"


stones.count(jewels) # => 3
stones.count(jewels) # => 3
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn count_jewels(stones: &str, jewels: &str) -> u8 {
<syntaxhighlight lang="rust">fn count_jewels(stones: &str, jewels: &str) -> u8 {
let mut count: u8 = 0;
let mut count: u8 = 0;
for cur_char in stones.chars() {
for cur_char in stones.chars() {
Line 1,711: Line 1,711:
println!("{}", count_jewels("ZZ", "z"));
println!("{}", count_jewels("ZZ", "z"));
}
}
</syntaxhighlight>
</lang>
Output:<pre>3
Output:<pre>3
0</pre>
0</pre>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>object JewelsStones extends App {
<syntaxhighlight lang="scala">object JewelsStones extends App {
def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))
def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))


println(countJewels("aAAbbbb", "aA"))
println(countJewels("aAAbbbb", "aA"))
println(countJewels("ZZ", "z"))
println(countJewels("ZZ", "z"))
}</lang>
}</syntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/Cz1HXAT/0 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/7ZCCN5hISRuDqLWTKVBHow Scastie (JVM)].
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/Cz1HXAT/0 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/7ZCCN5hISRuDqLWTKVBHow Scastie (JVM)].


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func countJewels(s, j) {
<syntaxhighlight lang="ruby">func countJewels(s, j) {
s.chars.count { |c|
s.chars.count { |c|
j.contains(c)
j.contains(c)
Line 1,732: Line 1,732:


say countJewels("aAAbbbb", "aA") #=> 3
say countJewels("aAAbbbb", "aA") #=> 3
say countJewels("ZZ", "z") #=> 0</lang>
say countJewels("ZZ", "z") #=> 0</syntaxhighlight>


=={{header|Snobol}}==
=={{header|Snobol}}==
<lang snobol>* See how many jewels are among the stones
<syntaxhighlight lang="snobol">* See how many jewels are among the stones
DEFINE('JEWELS(JWL,STN)') :(JEWELS_END)
DEFINE('JEWELS(JWL,STN)') :(JEWELS_END)
JEWELS JEWELS = 0
JEWELS JEWELS = 0
Line 1,747: Line 1,747:
* Example with no jewels (prints 0)
* Example with no jewels (prints 0)
OUTPUT = JEWELS('z','ZZ')
OUTPUT = JEWELS('z','ZZ')
END</lang>
END</syntaxhighlight>


{{out}}
{{out}}
Line 1,755: Line 1,755:


=={{header|SQL}}==
=={{header|SQL}}==
<lang SQL>-- See how many jewels are among the stones
<syntaxhighlight lang="sql">-- See how many jewels are among the stones
declare @S varchar(1024) = 'AaBbCcAa'
declare @S varchar(1024) = 'AaBbCcAa'
, @J varchar(1024) = 'aA';
, @J varchar(1024) = 'aA';
Line 1,788: Line 1,788:
end
end
print 'J='+@J+' S='+@S+' TOTAL = '+cast(@TCNT as varchar(8));
print 'J='+@J+' S='+@S+' TOTAL = '+cast(@TCNT as varchar(8));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,796: Line 1,796:


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func countJewels(_ stones: String, _ jewels: String) -> Int {
<syntaxhighlight lang="swift">func countJewels(_ stones: String, _ jewels: String) -> Int {
return stones.map({ jewels.contains($0) ? 1 : 0 }).reduce(0, +)
return stones.map({ jewels.contains($0) ? 1 : 0 }).reduce(0, +)
}
}


print(countJewels("aAAbbbb", "aA"))
print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))</lang>
print(countJewels("ZZ", "z"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,809: Line 1,809:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang Tcl>proc shavej {stones jewels} {
<syntaxhighlight lang="tcl">proc shavej {stones jewels} {
set n 0
set n 0
foreach c [split $stones {}] {
foreach c [split $stones {}] {
Line 1,817: Line 1,817:
}
}
puts [shavej aAAbbbb aA]
puts [shavej aAAbbbb aA]
puts [shavej ZZ z]</lang>
puts [shavej ZZ z]</syntaxhighlight>
{{out}}
{{out}}
3
3
Line 1,823: Line 1,823:


=={{header|Terraform}}==
=={{header|Terraform}}==
<lang hcl>variable "jewels" {
<syntaxhighlight lang="hcl">variable "jewels" {
default = "aA"
default = "aA"
}
}
Line 1,839: Line 1,839:
output "jewel_count" {
output "jewel_count" {
value = length(local.found_jewels)
value = length(local.found_jewels)
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,860: Line 1,860:


=={{header|Transd}}==
=={{header|Transd}}==
<lang Scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 1,870: Line 1,870:
_start: (λ (lout (countJewels "aA" "aAAbbbb"))
_start: (λ (lout (countJewels "aA" "aAAbbbb"))
(lout (countJewels "b" "BB")))
(lout (countJewels "b" "BB")))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,878: Line 1,878:


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Function count_jewels(stones As String, jewels As String) As Integer
{{trans|Phix}}<syntaxhighlight lang="vb">Function count_jewels(stones As String, jewels As String) As Integer
Dim res As Integer: res = 0
Dim res As Integer: res = 0
For i = 1 To Len(stones)
For i = 1 To Len(stones)
Line 1,888: Line 1,888:
Debug.Print count_jewels("aAAbbbb", "aA")
Debug.Print count_jewels("aAAbbbb", "aA")
Debug.Print count_jewels("ZZ", "z")
Debug.Print count_jewels("ZZ", "z")
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 3
<pre> 3
0 </pre>
0 </pre>
Line 1,894: Line 1,894:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function Count(stones As String, jewels As String) As Integer
Function Count(stones As String, jewels As String) As Integer
Line 1,906: Line 1,906:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,913: Line 1,913:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>fn js(stones string, jewels string) int {
<syntaxhighlight lang="vlang">fn js(stones string, jewels string) int {
mut n := 0
mut n := 0
for b in stones.bytes() {
for b in stones.bytes() {
Line 1,925: Line 1,925:
fn main() {
fn main() {
println(js("aAAbbbb", "aA"))
println(js("aAAbbbb", "aA"))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,934: Line 1,934:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>var countJewels = Fn.new { |s, j| s.count { |c| j.contains(c) } }
<syntaxhighlight lang="ecmascript">var countJewels = Fn.new { |s, j| s.count { |c| j.contains(c) } }


System.print(countJewels.call("aAAbbbb", "aA"))
System.print(countJewels.call("aAAbbbb", "aA"))
System.print(countJewels.call("ZZ", "z"))</lang>
System.print(countJewels.call("ZZ", "z"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,946: Line 1,946:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \Use zero-terminated strings
<syntaxhighlight lang="xpl0">string 0; \Use zero-terminated strings


func Count(Stones, Jewels);
func Count(Stones, Jewels);
Line 1,968: Line 1,968:
IntOut(0, Count("ZZ", "z")); CrLf(0);
IntOut(0, Count("ZZ", "z")); CrLf(0);
IntOut(0, Count("pack my box with five dozen liquor jugs", "aeiou")); CrLf(0);
IntOut(0, Count("pack my box with five dozen liquor jugs", "aeiou")); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,978: Line 1,978:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn countJewels(a,b){ a.inCommon(b).len() }</lang>
<syntaxhighlight lang="zkl">fcn countJewels(a,b){ a.inCommon(b).len() }</syntaxhighlight>
<lang zkl>println(countJewels("aAAbbbb", "aA"));
<syntaxhighlight lang="zkl">println(countJewels("aAAbbbb", "aA"));
println(countJewels("ZZ", "z"));</lang>
println(countJewels("ZZ", "z"));</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3

Revision as of 16:52, 27 August 2022


Task
Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task

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:

  1. Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
  2. A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
  3. The parameters do not need to have exactly the same names.
  4. Validating the arguments is unnecessary.

So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.

This task was inspired by this problem.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

Translation of: Python
F count_jewels(s, j)
   R sum(s.map(x -> Int(x C @j)))

print(count_jewels(‘aAAbbbb’, ‘aA’))
print(count_jewels(‘ZZ’, ‘z’))
Output:
3
0

8080 Assembly

	org	100h
	jmp	demo
	;;;	Count jewels.
	;;;	Input: BC = jewels, DE = stones.
	;;;	Output: BC = count
	;;;	Destroyed: A, DE, HL
jewel:	lxi	h,jarr	; Zero out the page of memory
	xra	a
jzero:	mov	m,a
	inr	l
	jnz	jzero
jrjwl:	ldax	b	; Get jewel
	inx	b
	mov	l,a	; Mark the corresponding byte in the array
	inr	m
	ana	a	; If 'jewel' is 0, we've reached the end
	jnz	jrjwl	; Otherwise, do next jewel
	lxi	b,0	; BC = count (we no longer need the jewel string)
jrstn:	ldax	d	; Get stone
	inx	d
	ana	a	; If zero, we're done
	rz
	mov	l,a	; Get corresponding byte in array 
	mov	a,m
	ana	a
	jz	jrstn	; If zero, it is not a jewel
	inx	b	; But otherwise, it is a jewel
	jmp	jrstn
	;;;	Demo code
demo:	lxi	b,jewels	; Set up registers
	lxi	d,stones
	call	jewel		; Call the function
	;;;	Print the number
	lxi	h,num	; Pointer to number string
	push	h	; Push to stack
	mov	h,b	; HL = number to print
	mov	l,c
	lxi	b,-10	; Divisor
dgt:	lxi	d,-1	; Quotient
dgtlp:	inx	d	; Divide using trial subtraction
	dad	b
	jc	dgtlp
	mvi	a,'0'+10
	add	l	; HL = remainder-10
	pop	h	; Get pointer
	dcx	h	; Decrement pointer
	mov	m,a	; Store digit
	push	h	; Put pointer back
	xchg		; Go on with new quotient
	mov	a,h	; If 0, we're done
	ana	l
	jnz	dgt	; If not 0, next digit
	pop	d	; Get pointer and put it in DE
	mvi	c,9	; CP/M syscall to print string
	jmp	5
	db	'*****'	; Placeholder for ASCII number output
num:	db	'$'
	;;;	Example from the task
jewels:	db	'aA',0
stones:	db	'aAAbbbb',0
	;;;	Next free page of memory is used for the jewel array
jpage:	equ	$/256+1
jarr:	equ	jpage*256
Output:
3


8086 Assembly

	cpu	8086
	bits	16
	org	100h
section	.text
	jmp	demo
	;;;	Count jewels.
	;;;	Input: DS:SI = jewels, DS:DX = stones
	;;;	Output: CX = how many stones are jewels
	;;;	Destroyed: AX, BX, SI, DI
jewel:	xor	ax,ax
	mov	cx,128		; Allocate 256 bytes (128 words) on stack
.zloop:	push	ax		; Set them all to zero
	loop	.zloop
	mov	di,sp		; DI = start of array
	xor	bh,bh
.sjwl:	lodsb			; Get jewel
	mov	bl,al
	inc	byte [ss:di+bx]	; Set corresponding byte
	test	al,al		; If not zero, there are more jewels
	jnz	.sjwl
	mov	si,dx		; Read stones
.sstn:	lodsb			; Get stone
	mov	bl,al		; Get corresponding byte
	mov	bl,[ss:di+bx]
	add	cx,bx		; Add to count (as word)
	test	al,al		; If not zero, there are more stones
	jnz	.sstn
	add	sp,256		; Otherwise, we are done - free the array
	dec	cx		; The string terminator is a 'jewel', so remove
	ret
	;;;	Demo
demo:	mov	si,jewels	; Set up registers
	mov	dx,stones
	call	jewel		; Call the function
	;;;	Print number 
	mov	ax,10		; Result is in CX
	xchg	ax,cx		; Set AX to result and CX to divisor (10)
	mov	bx,num		; Number pointer
dgt:	xor	dx,dx
	div	cx		; Divide AX by 10
	add	dl,'0'		; Remainder is in DX - add ASCII 0
	dec	bx		; Store digit in string
	mov	[bx],dl
	test	ax,ax		; Any more digits?
	jnz	dgt		; If so, next digit
	mov	dx,bx		; When done, print string
	mov	ah,9
	int	21h
	ret
section	.data
	db	'*****'		; Placeholder for ASCII number output
num:	db	'$'
stones:	db	'aAAbbbb',0	; Example from the task
jewels:	db	'aA',0
Output:
3

Ada

with Ada.Text_IO;

procedure Jewels_And_Stones is

   function Count (Jewels, Stones : in String) return Natural is
      Sum : Natural := 0;
   begin
      for J of Jewels loop
         for S of Stones loop
            if J = S then
               Sum := Sum + 1;
               exit;
            end if;
         end loop;
      end loop;
      return Sum;
   end Count;

   procedure Show (Jewels, Stones : in String) is
      use Ada.Text_IO;
   begin
      Put (Jewels);
      Set_Col (12); Put (Stones);
      Set_Col (20); Put (Count (Jewels => Jewels,
                                Stones => Stones)'Image);
      New_Line;
   end Show;

begin
   Show ("aAAbbbb", "aA");
   Show ("ZZ",      "z");
end Jewels_And_Stones;
Output:
aAAbbbb    aA       3
ZZ         z        0

ALGOL 68

BEGIN
    # procedure that counts the number of times the letters in jewels occur in stones #
    PROC count jewels = ( STRING stones, jewels )INT:
         BEGIN
             # count the occurences of each letter in stones #
             INT upper a pos = 0;
             INT lower a pos = 1 + ( ABS "Z" - ABS "A" );
             [ upper a pos : lower a pos + 26 ]INT letter counts;
             FOR c FROM LWB letter counts TO UPB letter counts DO letter counts[ c ] := 0 OD;
             FOR s pos FROM LWB stones TO UPB stones DO
                 CHAR s = stones[ s pos ];
                 IF   s >= "A" AND s <= "Z" THEN letter counts[ upper a pos + ( ABS s - ABS "A" ) ] +:= 1
                 ELIF s >= "a" AND s <= "z" THEN letter counts[ lower a pos + ( ABS s - ABS "a" ) ] +:= 1
                 FI
             OD;
             # sum the counts of the letters that appear in jewels #
             INT count := 0;
             FOR j pos FROM LWB jewels TO UPB jewels DO
                 CHAR j = jewels[ j pos ];
                 IF   j >= "A" AND j <= "Z" THEN count +:= letter counts[ upper a pos + ( ABS j - ABS "A" ) ]
                 ELIF j >= "a" AND j <= "z" THEN count +:= letter counts[ lower a pos + ( ABS j - ABS "a" ) ]
                 FI 
             OD;
             count
         END # count jewels # ;

    print( ( count jewels( "aAAbbbb", "aA" ), newline ) );
    print( ( count jewels( "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz"
                         , "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz"
                         )
           , newline
           )
         );
    print( ( count jewels( "AB", "" ), newline ) );
    print( ( count jewels( "ZZ", "z" ), newline ) )

END
Output:
         +3
        +52
         +0
         +0

APL

Works with: Dyalog APL
jewels  +/
Output:
      'aA' jewels 'aAAbbbb'
3


AppleScript

Functional

-- jewelCount :: String -> String -> Int
on jewelCount(jewels, stones)
    set js to chars(jewels)
    script
        on |λ|(a, c)
            if elem(c, jewels) then
                a + 1
            else
                a
            end if
        end |λ|
    end script
    foldl(result, 0, chars(stones))
end jewelCount

-- OR in terms of filter
-- jewelCount :: String -> String -> Int
on jewelCount2(jewels, stones)
    script
        on |λ|(c)
            elem(c, jewels)
        end |λ|
    end script
    length of filter(result, stones)
end jewelCount2

-- TEST --------------------------------------------------
on run
    
    unlines(map(uncurry(jewelCount), ¬
        {Tuple("aA", "aAAbbbb"), Tuple("z", "ZZ")}))
    
end run


-- GENERIC FUNCTIONS -------------------------------------

-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
    {type:"Tuple", |1|:a, |2|:b}
end Tuple

-- chars :: String -> [Char]
on chars(s)
    characters of s
end chars

-- elem :: Eq a => a -> [a] -> Bool
on elem(x, xs)
    considering case
        xs contains x
    end considering
end elem

-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
    tell mReturn(f)
        set lst to {}
        set lng to length of xs
        repeat with i from 1 to lng
            set v to item i of xs
            if |λ|(v, i, xs) then set end of lst to v
        end repeat
        return lst
    end tell
end filter

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- Returns a function on a single tuple (containing 2 arguments)
-- derived from an equivalent function with 2 distinct arguments
-- uncurry :: (a -> b -> c) -> ((a, b) -> c)
on uncurry(f)
    script
        property mf : mReturn(f)'s |λ|
        on |λ|(pair)
            mf(|1| of pair, |2| of pair)
        end |λ|
    end script
end uncurry

-- unlines :: [String] -> String
on unlines(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines
Output:
3
0

Idiomatic

on jewelsAndStones(stones, jewels)
    set counter to 0
    considering case
        repeat with thisCharacter in stones
            if (thisCharacter is in jewels) then set counter to counter + 1
        end repeat
    end considering
    
    return counter
end jewelsAndStones

jewelsAndStones("aAAbBbb", "aAb")
Output:
6

Arturo

count: function [jewels,stones][
    size select split stones => [in? & jewels]
]

print count "aA" "aAAbbbb"
Output:
3

AutoHotkey

JewelsandStones(ss, jj){
	for each, jewel in StrSplit(jj)
		for each, stone in StrSplit(ss)
			if (stone == jewel)
				num++
	return num
}

Example:

MsgBox % JewelsandStones("aAAbbbbz", "aAZ")
return

Outputs:

3

AWK

# syntax: GAWK -f JEWELS_AND_STONES.AWK
BEGIN {
    printf("%d\n",count("aAAbbbb","aA"))
    printf("%d\n",count("ZZ","z"))
    exit(0)
}
function count(stone,jewel,  i,total) {
    for (i=1; i<length(stone); i++) {
      if (jewel ~ substr(stone,i,1)) {
        total++
      }
    }
    return(total)
}
Output:
3
0

BASIC

10 READ N%
20 FOR A%=1 TO N%
30 READ J$,S$
40 GOSUB 100
50 PRINT S$;" in ";J$;":";J%
60 NEXT
70 END

100 REM Count how many stones (S$) are jewels (J$). 
110 DIM J%(127)
120 J%=0
130 FOR I%=1 TO LEN(J$): J%(ASC(MID$(J$,I%,1)))=1: NEXT
140 FOR I%=1 TO LEN(S$): J%=J%+J%(ASC(MID$(S$,I%,1))): NEXT
150 ERASE J%
160 RETURN

200 DATA 2
210 DATA "aA","aAAbbbb"
220 DATA "z","ZZZZ"
Output:
aAAbbbb in aA: 3
ZZZZ in z: 0

BASIC256

function contar_joyas(piedras, joyas)
	cont = 0
	for i = 1 to length(piedras)
		bc = instr(joyas, mid(piedras, i, 1), 1)
		if bc <> 0 then cont += 1
	next i
	return cont
end function

print contar_joyas("aAAbbbb", "aA")
print contar_joyas("ZZ", "z")
print contar_joyas("ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
print contar_joyas("AB", "")
Output:
Igual que la entrada de FreeBASIC.

BCPL

get "libhdr"

let jewels(j, s) = valof
$(  let jewel = vec 255
    let count = 0
    for i = 0 to 255 do jewel!i := false
    for i = 1 to j%0 do jewel!(j%i) := true
    for i = 1 to s%0 do 
        if jewel!(s%i) then
            count := count + 1
    resultis count
$)

let show(j, s) be
    writef("*"%S*" in *"%S*": %N*N", j, s, jewels(j, s))

let start() be
$(  show("aA", "aAAbbbb")
    show("z", "ZZ")
$)
Output:
"aA" in "aAAbbbb": 3
"z" in "ZZ": 0

BQN

Similar in nature to APL, mostly due to how trivial the problem is in an array language.

Jewels+´˜
  "aA" Jewels "aAAbbbb"
3

Bracmat

  ( f
  =   stones jewels N
    .   !arg:(?stones.?jewels)
      & 0:?N
      & ( @( !stones
           :   ?
               (   %@
                 : [%(   @(!jewels:? !sjt ?)
                       & 1+!N:?N
                     |
                     )
               & ~
               )
               ?
           )
        | !N
        )
  )
& f$(aAAbbbb.aA)

Output

3

C

Translation of: Kotlin
#include <stdio.h>
#include <string.h>

int count_jewels(const char *s, const char *j) {
    int count = 0;
    for ( ; *s; ++s) if (strchr(j, *s)) ++count;
    return count;
}

int main() {
    printf("%d\n", count_jewels("aAAbbbb", "aA"));
    printf("%d\n", count_jewels("ZZ", "z"));
    return 0;
}
Output:
3
0

C#

using System;
using System.Linq;

public class Program
{
    public static void Main() {
        Console.WriteLine(Count("aAAbbbb", "Aa"));
        Console.WriteLine(Count("ZZ", "z"));
    }

    private static int Count(string stones, string jewels) {
        var bag = jewels.ToHashSet();
        return stones.Count(bag.Contains);
    }
}
Output:
3
0

C++

Translation of: D
#include <algorithm>
#include <iostream>

int countJewels(const std::string& s, const std::string& j) {
    int count = 0;
    for (char c : s) {
        if (j.find(c) != std::string::npos) {
            count++;
        }
    }
    return count;
}

int main() {
    using namespace std;

    cout << countJewels("aAAbbbb", "aA") << endl;
    cout << countJewels("ZZ", "z") << endl;

    return 0;
}
Output:
3
0

CLU

count_jewels = proc (jewels, stones: string) returns (int)
    is_jewel: array[bool] := array[bool]$fill(0, 256, false)
    for c: char in string$chars(jewels) do
        is_jewel[char$c2i(c)] := true
    end
    
    n_jewels: int := 0
    for c: char in string$chars(stones) do
        if is_jewel[char$c2i(c)] then n_jewels := n_jewels + 1 end
    end
    return (n_jewels)
end count_jewels

show = proc (jewels, stones: string)
    po: stream := stream$primary_output()
    
    stream$putl(po, "\"" || jewels || "\" in \"" || stones || "\": "
                || int$unparse(count_jewels(jewels, stones)))
end show

start_up = proc ()
    show("aA", "aAAbbbb")
end start_up
Output:
"aA" in "aAAbbbb": 3

Cowgol

include "cowgol.coh";

sub count_jewels(stones: [uint8], jewels: [uint8]): (count: uint16) is
    var jewel_mark: uint8[256];
    MemZero(&jewel_mark as [uint8], 256);

    while [jewels] != 0 loop
        jewel_mark[[jewels]] := 1;
        jewels := @next jewels;
    end loop;

    count := 0;
    while [stones] != 0 loop
        count := count + jewel_mark[[stones]] as uint16;
        stones := @next stones;
    end loop;
end sub;

sub print_and_count(stones: [uint8], jewels: [uint8]) is
    print(jewels);
    print(" in ");
    print(stones);
    print(": ");
    print_i16(count_jewels(stones, jewels));
    print_nl();
end sub;

print_and_count("aAAbbbb", "aA");
print_and_count("ZZ", "z");
Output:
aA in aAAbbbb: 3
z in ZZ: 0

Crystal

stones, jewels = "aAAbbbb", "aA"
stones.count(jewels) # => 3

# The above solution works for that case, but fails with certain other "jewels":
stones, jewels = "aA^Bb", "^b"
stones.count(jewels) # => 4
# '^b' in the "jewels" is read as "characters other than 'b'".

# This works as intended though:
stones.count { |c| jewels.chars.includes?(c) } # => 2

D

Translation of: Kotlin
import std.algorithm;
import std.stdio;

int countJewels(string s, string j) {
    int count;
    foreach (c; s) {
        if (j.canFind(c)) {
            count++;
        }
    }
    return count;
}

void main() {
    countJewels("aAAbbbb", "aA").writeln;
    countJewels("ZZ", "z").writeln;
}
Output:
3
0

Draco

proc nonrec count_jewels(*char jewels, stones) word:
    [256] bool jewel;
    word count;
    byte i;
    char c;
    
    for i from 0 upto 255 do jewel[i] := false od;
    while c := jewels*; c ~= '\e' do
        jewel[c] := true;
        jewels := jewels + 1;
    od;
    
    count := 0;
    while c := stones*; c ~= '\e' do
        if jewel[c] then count := count + 1 fi;
        stones := stones + 1
    od;
    count
corp

proc nonrec show(*char jewels, stones) void:
    writeln("'", jewels, "' in '", stones, "': ", count_jewels(jewels, stones))
corp

proc nonrec main() void:
    show("aA", "aAAbbbb");
    show("z", "ZZ")
corp
Output:
'aA' in 'aAAbbbb': 3
'z' in 'ZZ': 0

Dyalect

Translation of: Swift
func countJewels(stones, jewels) {
    stones.Iterate().Map(x => jewels.Contains(x) ? 1 : 0).Reduce((x,y) => x + y, 0)
}
 
print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))
Output:
3
0

F#

let fN jewels stones=stones|>Seq.filter(fun n->Seq.contains n jewels)|>Seq.length
printfn "%d" (fN "aA" "aAAbbbb")
Output:
3

Factor

USING: kernel prettyprint sequences ;

: count-jewels ( stones jewels -- n ) [ member? ] curry count ;

"aAAbbbb" "aA"
"ZZ" "z" [ count-jewels . ] 2bi@
Output:
3
0

Euphoria

function number_of(object jewels, object stones) -- why limit ourselves to strings?
integer ct = 0
    for i = 1 to length(stones) do
        ct += find(stones[i],jewels) != 0
    end for
    return ct
end function

? number_of("aA","aAAbbbb")
? number_of("z","ZZ")
? number_of({1,"Boo",3},{1,2,3,'A',"Boo",3}) -- might as well send a list of things to find, not just one!
Output:
3
0
4 -- 1 is found once, "Boo" is found once, and 3 is found twice = 4 things in the search list were found in the target list

FreeBASIC

function contar_joyas(piedras as string, joyas as string) as integer
    dim as integer bc, cont: cont = 0
    for i as integer = 1 to len(piedras)
        bc = instr(1, joyas, mid(piedras, i, 1))
        if bc <> 0 then cont += 1
    next i
    contar_joyas = cont
end function

print contar_joyas("aAAbbbb", "aA")
print contar_joyas("ZZ", "z")
print contar_joyas("ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz", _
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrstuvwxyz")
print contar_joyas("AB", "")
Output:
3
0
53
0

Go

Four solutions are shown here. The first of two simpler solutions iterates over the stone string in an outer loop and makes repeated searches into the jewel string, incrementing a count each time it finds a stone in the jewels. The second of the simpler solutions reverses that, iterating over the jewel string in the outer loop and accumulating counts of matching stones. This solution works because we are told that all letters of the jewel string must be unique. These two solutions are simple but are both O(|j|*|s|).

The two more complex solutions are analogous to the two simpler ones but build a set or multiset as preprocessing step, replacing the inner O(n) operation with an O(1) operation. The resulting complexity in each case is O(|j|+|s|).

Outer loop stones, index into jewels:

package main
  
import (
    "fmt"
    "strings"
)

func js(stones, jewels string) (n int) {
    for _, b := range []byte(stones) {
        if strings.IndexByte(jewels, b) >= 0 {
            n++
        }
    }
    return
}

func main() {
    fmt.Println(js("aAAbbbb", "aA"))
}
Output:
3

Outer loop jewels, count stones:

func js(stones, jewels string) (n int) {
    for _, b := range []byte(jewels) {
        n += strings.Count(stones, string(b))
    }
    return
}

Construct jewel set, then loop over stones:

func js(stones, jewels string) (n int) {
    var jSet ['z' + 1]int
    for _, b := range []byte(jewels) {
        jSet[b] = 1
    }
    for _, b := range []byte(stones) {
        n += jSet[b]
    }
    return
}

Construct stone multiset, then loop over jewels:

func js(stones, jewels string) (n int) {
    var sset ['z' + 1]int
    for _, b := range []byte(stones) {
        sset[b]++
    }
    for _, b := range []byte(jewels) {
        n += sset[b]
    }
    return
}

Haskell

jewelCount
  :: Eq a
  => [a] -> [a] -> Int
jewelCount jewels = foldr go 0
  where
    go c
      | c `elem` jewels = succ
      | otherwise = id

--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ uncurry jewelCount <$> [("aA", "aAAbbbb"), ("z", "ZZ")]
Output:
3
0

Or in terms of filter rather than foldr

jewelCount
  :: Eq a
  => [a] -> [a] -> Int
jewelCount jewels = length . filter (`elem` jewels)

--------------------------- TEST -------------------------
main :: IO ()
main = do
  print $ jewelCount "aA" "aAAbbbb"
  print $ jewelCount "z" "ZZ"
Output:
3
0

J

   NB. jewels sums a raveled equality table
   NB. use: x jewels y  x are the stones, y are the jewels.
   intersect =: -.^:2
   jewels =: ([: +/ [: , =/~) ~.@:intersect&Alpha_j_

   'aAAbbbb ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz' jewels&>&;: 'aA ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
3 52

   'none' jewels ''
0
   'ZZ' jewels 'z'
0

Java

import java.util.HashSet;
import java.util.Set;

public class App {
    private static int countJewels(String stones, String jewels) {
        Set<Character> bag = new HashSet<>();
        for (char c : jewels.toCharArray()) {
            bag.add(c);
        }

        int count = 0;
        for (char c : stones.toCharArray()) {
            if (bag.contains(c)) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        System.out.println(countJewels("aAAbbbb", "aA"));
        System.out.println(countJewels("ZZ", "z"));
    }
}
Output:
3
0

JavaScript

(() => {

    // jewelCount :: String -> String -> Int
    const jewelCount = (j, s) => {
        const js = j.split('');
        return s.split('')
            .reduce((a, c) => js.includes(c) ? a + 1 : a, 0)
    };

    // TEST -----------------------------------------------
    return [
            ['aA', 'aAAbbbb'],
            ['z', 'ZZ']
        ]
        .map(x => jewelCount(...x))
})();
Output:
[3, 0]

jq

$ jq -n --arg stones aAAbbbb --arg jewels aA '
  [$stones|split("") as $s|$jewels|split("") as $j|$s[]|
  select(. as $c|$j|contains([$c]))]|length'
Output:
3

Julia

Module:

module Jewels

count(s, j) = Base.count(x  j for x in s)

end  # module Jewels

Main:

@show Jewels.count("aAAbbbb", "aA")
@show Jewels.count("ZZ", "z")
Output:
Jewels.count("aAAbbbb", "aA") = 3
Jewels.count("ZZ", "z") = 0

Kotlin

// Version 1.2.40

fun countJewels(s: String, j: String) = s.count { it in j }

fun main(args: Array<String>) {
    println(countJewels("aAAbbbb", "aA"))
    println(countJewels("ZZ", "z"))
}
Output:
3
0

Lambdatalk

{def countjewels
 {def countjewels.r
  {lambda {:a :b :c}
   {if {A.empty? :a}
    then :c
    else {countjewels.r {A.rest :a}
                        :b
                        {if {= {A.in? {A.first :a} :b} -1}
                         then :c
                         else {+ :c 1}}}}}}
 {lambda {:a :b}
  {countjewels.r {A.split :a} {A.split :b} 0}}} 
-> countjewels

{countjewels aAAbbbb aA} -> 3
{countjewels ZZ z}       -> 0

Lua

Translation of: C
function count_jewels(s, j)
    local count = 0
    for i=1,#s do
        local c = s:sub(i,i)
        if string.match(j, c) then
            count = count + 1
        end
    end
    return count
end

print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("ZZ", "z"))
Output:
3
0

Maple

count_jewel := proc(stones, jewels)
	local count, j, letter:
	j := convert(jewels,set):
	count := 0:
	for letter in stones do
		if (member(letter, j)) then
			count++:
		end if:
	end do:
	return count:
end proc:
count_jewel("aAAbbbb", "aA")
Output:
3

Mathematica / Wolfram Language

JewelsStones[j_String, s_String] := Count[MemberQ[Characters[j], #] & /@ Characters[s], True]
JewelsStones["aA", "aAAbbbb"]
JewelsStones["ZZ", "z"]
Output:
3
0

MATLAB / Octave

    function s = count_jewels(stones,jewels)
    s=0;
    for c=jewels
        s=s+sum(c==stones);
    end
    %!test
    %! assert(count_jewels('aAAbbbb','aA'),3)
    %!test
    %! assert(count_jewels('ZZ','z'),0)

min

Works with: min version 0.19.6
(('' '' '') => spread if) :if?

((1 0 if?) concat map sum) :count

(swap indexof -1 !=) :member?

(("" split) dip 'member? cons count) :count-jewels

"aAAbbbb" "aA" count-jewels puts!
"ZZ" "z" count-jewels puts!
Output:
3
0

Modula-2

MODULE Jewels;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
    FormatString("%i", buf, n);
    WriteString(buf)
END WriteInt;

PROCEDURE CountJewels(s,j : ARRAY OF CHAR) : INTEGER;
VAR c,i,k : CARDINAL;
BEGIN
    c :=0;

    FOR i:=0 TO HIGH(s) DO
        FOR k:=0 TO HIGH(j) DO
            IF (j[k]#0C) AND (s[i]#0C) AND (j[k]=s[i]) THEN
                INC(c);
                BREAK
            END
        END
    END;

    RETURN c
END CountJewels;

BEGIN
    WriteInt(CountJewels("aAAbbbb", "aA"));
    WriteLn;
    WriteInt(CountJewels("ZZ", "z"));
    WriteLn;

    ReadChar
END Jewels.
Output:
3
0

Nim

import sequtils

func countJewels(stones, jewels: string): Natural =
  stones.countIt(it in jewels)

echo countJewels("aAAbbbb", "aA")
echo countJewels("ZZ", "z")
Output:
3
0

Objeck

Translation of: Java
use Collection.Generic;

class JewelsStones {
  function : Main(args : String[]) ~ Nil {
    Count("aAAbbbb", "aA")->PrintLine();
    Count("ZZ", "z")->PrintLine();
  }

  function : Count(stones : String, jewels : String) ~ Int {
    bag := Set->New()<CharHolder>;

    each(i : jewels) {
      bag->Insert(jewels->Get(i));
    };

    count := 0;
    each(i : stones) {
      if(bag->Has(stones->Get(i))) {
        count++;
      };
    };
 
    return count;
  }
}
Output:
3
0

Perl

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';
Output:
3
0

Alternate using regex

#!/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
Output:
aAAbbbb aA = 3
aAAbbbb abc = 5
ZZ z = 0

Phix

function count_jewels(string stones, jewels)
    integer res = 0
    for i=1 to length(stones) do
        res += find(stones[i],jewels)!=0
    end for
    return res
end function
?count_jewels("aAAbbbb","aA")
?count_jewels("ZZ","z")
Output:
3
0

Picat

List comprehension

jewels_and_stones1(Jewels,Stones) = sum([1 : S in Stones, J in Jewels, S == J]).

Recursion

jewels_and_stones2(Jewels,Stones) = N =>
  jewels_and_stones2(Jewels,Stones,0,N).

jewels_and_stones2([],_Stones,N,N).
jewels_and_stones2([J|Jewels],[S|Stones],N0,N) :-
  jewels_and_stones2_(J,[S|Stones],0,JN),
  jewels_and_stones2(Jewels,Stones,N0+JN,N).

% Check just this jewel on all the stones
jewels_and_stones2_(_J,[],N,N).
jewels_and_stones2_(J,[S|Stones],N0,N) :-
  ( J == S ->
     N1 = N0+1
    ;
    N1 = N0
  ),
  jewels_and_stones2_(J,Stones,N1,N).

Foreach loop

jewels_and_stones3(Jewels,Stones) = N =>
  N = 0,
  foreach(J in Jewels, S in Stones)
     if J == S then
       N := N + 1
     end
  end.

Test

go =>
  Tests = [["aA","aAAbbbb"],
           ["z","ZZ"]
           ],
  println(tests=Tests),
  foreach([Jewels,Stones] in Tests)
    println([jewels=Jewels,stone=Stones]),
    println(js1=jewels_and_stones1(Jewels,Stones)),
    println(js2=jewels_and_stones2(Jewels,Stones)),
    println(js3=jewels_and_stones3(Jewels,Stones)),
    nl
  end,
  nl.
Output:
tests = [[aA,aAAbbbb],[z,ZZ]]
[jewels = aA,stone = aAAbbbb]
js1 = 3
js2 = 3
js3 = 3

[jewels = z,stone = ZZ]
js1 = 0
js2 = 0
js3 = 0

Benchmark

For a larger test we can see the differences between the three approaches. Here are 100 000 000 random stones and (atmost) 15 jewels (we remove any duplicate jewel).

go2 =>
  Alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  Len = Alpha.len,
  _ = random2(),
  NumStones = 100_000_000,
  NumJewels = 15, % Atmost number of jewels (duplicates are removed)
  
  Stones = [Alpha[random(1,Len)] : _ in 1..NumStones],
  Jewels = [Alpha[random(1,Len)] : _ in 1..NumJewels].sort_remove_dups,
  println(jewels=Jewels),
  nl,  
  time(println(js1=jewels_and_stones1(Jewels,Stones))),
  time(println(js2=jewels_and_stones2(Jewels,Stones))),
  time(println(js3=jewels_and_stones3(Jewels,Stones))),
  nl.
Output:
NumStones: 100_000_000  NumJewels = 15
jewels = TwurtRabSXx

js1 = 21154798

CPU time 15.087 seconds.

js2 = 21154796

CPU time 11.024 seconds.

js3 = 21154798

CPU time 11.94 seconds.

The recursion approach (jewels_and_stones2/2) is a little faster than the loop approach (jewels_and_stones/3).


PL/M

100H:

/* FIND JEWELS AMONG STONES */
COUNT$JEWELS: PROCEDURE (JEWELS, STONES) BYTE;
    DECLARE (JEWELS, STONES) ADDRESS;
    DECLARE (J BASED JEWELS, S BASED STONES) BYTE;
    DECLARE JFLAG (256) BYTE, I BYTE;
   
    /* ZERO JEWEL FLAGS */
    DO I=0 TO 255;
        JFLAG(I) = 0;
    END;
    
    /* LOOP THROUGH JEWELS AND MARK THEM */
    DO WHILE J <> '$';
        JFLAG(J) = 1;
        JEWELS = JEWELS + 1;
    END;
    
    /* COUNT THE JEWELS AMONG THE STONES */
    I = 0;
    DO WHILE S <> '$';
        I = I + JFLAG(S);
        STONES = STONES + 1;
    END;
    RETURN I;
END COUNT$JEWELS;

/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PRINT: PROCEDURE (STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
END PRINT;

/* NUMERIC OUTPUT */
PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (4) BYTE INITIAL ('...$');
    DECLARE P ADDRESS, (N, C BASED P) BYTE;
    P = .S(3);
DIGIT:
    P = P-1;
    C = N MOD 10 + '0';
    N = N/10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

/* PRINT JEWELS, STONES, AND AMOUNT OF JEWELS IN STONES */
TEST: PROCEDURE (J, S);
    DECLARE (J, S) ADDRESS;
    CALL PRINT(.'''$');
    CALL PRINT(J);
    CALL PRINT(.''' IN ''$');
    CALL PRINT(S);
    CALL PRINT(.''': $');
    CALL PRINT$NUMBER(COUNT$JEWELS(J, S));
    CALL PRINT(.(13,10,'$'));
END TEST;

/* UNFORTUNATELY, THE PL/M COMPILER ACCEPTS A VERY RESTRICTED CHARACTER SET
   IN THE SOURCE CODE. (IT IS THE INTERSECTION OF VARIOUS POPULAR CHARSETS
   FROM THE 1960S.) THIS CHARACTER SET DOES NOT INCLUDE LOWERCASE LETTERS.
   HOWEVER, THIS CODE ASSUMES THE ASCII CHARACTER SET ANYWAY.
   WE CAN INCLUDE LOWERCASE LETTERS ... BY WRITING THEIR ASCII CODES. 
   THE OUTPUT WILL BE CORRECT OF COURSE. */

CALL TEST(.( 97,'A$' ), .( 97,'AA',98,98,98,98,'$' )); 
CALL TEST(.( 122,'$' ), .( 'ZZZZ$' ));

CALL BDOS(0,0);
EOF
Output:
'aA' IN 'aAAbbbb': 3
'z' IN 'ZZZZ': 0

Prolog

:- system:set_prolog_flag(double_quotes,codes) .

count_jewels(STONEs0,JEWELs0,COUNT)
:-
findall(X,(member(X,JEWELs0),member(X,STONEs0)),ALLs) ,
length(ALLs,COUNT)
.
Output:
/*
?- count_jewels("aAAbbbb","aA",N).
N = 3.

?- count_jewels("ZZ","z",N).
N = 0.

?-  count_jewels("aAAbbbb","bcd",N) .
N = 4.

?-
*/

alternative version

Works with: SWI Prolog
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).
Output:
Welcome to SWI-Prolog (threaded, 64 bits, version 8.0.2)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit http://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- count_jewels("aAAbbbb", "aA", N).
N = 3.

Python

def countJewels(s, j):
    return sum(x in j for x in s)

print countJewels("aAAbbbb", "aA")
print countJewels("ZZ", "z")
Output:
3
0

Python 3 Alternative

def countJewels(stones, jewels):
    jewelset = set(jewels)
    return sum(1 for stone in stones if stone in jewelset)

print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))
Output:
3
0

R

J_n_S <- function(stones  ="aAAbbbb", jewels = "aA") {
  stones <- unlist(strsplit(stones, split = "")) # obtain a character vector
  jewels <- unlist(strsplit(jewels, split = ""))
  count <- sum(stones %in% jewels)
}

print(J_n_S("aAAbbbb", "aA"))
print(J_n_S("ZZ", "z"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH"))
Output:
> print(J_n_S("aAAbbbb", "aA"))
[1] 3
> print(J_n_S("ZZ", "z"))
[1] 0
> print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH"))
[1] 16

Quackery

  [ 0 0 rot 
    witheach [ bit | ] 
    rot witheach
      [ bit over & if 
          [ dip 1+ ] ] 
    drop ]             is j&s ( $ $ --> n )

  $ "aAAbbbb" $  "aA" j&s echo
Output:
3

Racket

#lang racket

(define (jewels-and-stones stones jewels)
  (length (filter (curryr member (string->list jewels)) (string->list stones))))

(module+ main
  (jewels-and-stones "aAAbbbb" "aA")
  (jewels-and-stones "ZZ" "z"))
Output:
3
0

Raku

(formerly Perl 6)

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';
Output:
3
0

Red

Red [
    title: "Jewels and stones"
    red-version: 0.6.4
]

count: function [
    "Returns the number of values in a block for which a function returns true"
    values [any-list! string!] "The values from which to count"
    fn [function!] "A function that returns true or false"
][
    count: 0
    foreach value values [if fn value [count: count + 1]]
    count
]

count-jewels: function [
    "Returns the count of 'jewels' in the 'stones'"
    stones "The values to search for jewels"
    jewels "The values to count in the stones"
][
    result: 0
    foreach jewel jewels [
        result: result + count stones function [stone][stone = jewel]
    ]
]

print count-jewels "aAAbbbb" "aA"
print count-jewels "ZZ" "z"
Output:
3
0

REXX

Programming note:   a check is made so that only (Latin) letters are counted as a match.

/*REXX pgm counts how many letters (in the 1st string) are in common with the 2nd string*/
say  count('aAAbbbb', "aA")
say  count('ZZ'     , "z" )
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
count: procedure;  parse arg stones,jewels       /*obtain the two strings specified.    */
       #= 0                                      /*initialize the variable  #  to  zero.*/
                   do j=1  for length(stones)    /*scan STONES for matching JEWELS chars*/
                   x= substr(stones, j, 1)       /*obtain a character of the STONES var.*/
                   if datatype(x, 'M')  then if pos(x, jewels)\==0  then #= # + 1
                   end   /*j*/                   /* [↑]  if a letter and a match, bump #*/
       return #                                  /*return the number of common letters. */
output   when using the default inputs:
3
0

Ring

# Project  Jewels and Stones
 
jewels = "aA"
stones = "aAAbbbb"
see jewelsandstones(jewels,stones) + nl
jewels = "z"
stones = "ZZ"
see jewelsandstones(jewels,stones) + nl

func jewelsandstones(jewels,stones)
        num = 0
        for n = 1 to len(stones)
             pos = substr(jewels,stones[n])
             if pos > 0
                num = num + 1
             ok
        next
        return num

Output:

3
0

Ruby

stones, jewels = "aAAbbbb", "aA"

stones.count(jewels)  # => 3

Rust

fn count_jewels(stones: &str, jewels: &str) -> u8 {
    let mut count: u8 = 0;
    for cur_char in stones.chars() {
        if jewels.contains(cur_char) {
            count += 1;
        }
    }
    count
}
fn main() {
    println!("{}", count_jewels("aAAbbbb", "aA"));
    println!("{}", count_jewels("ZZ", "z"));
}

Output:

3
0

Scala

object JewelsStones extends App {
  def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))

  println(countJewels("aAAbbbb", "aA"))
  println(countJewels("ZZ", "z"))
}
Output:

See it in running in your browser by ScalaFiddle (JavaScript) or by Scastie (JVM).

Sidef

func countJewels(s, j) {
    s.chars.count { |c|
        j.contains(c)
    }
}

say countJewels("aAAbbbb", "aA")    #=> 3
say countJewels("ZZ", "z")          #=> 0

Snobol

*       See how many jewels are among the stones
        DEFINE('JEWELS(JWL,STN)')               :(JEWELS_END)
JEWELS  JEWELS = 0
        JWL = ANY(JWL)
JMATCH  STN JWL = ''                            :F(RETURN)
        JEWELS = JEWELS + 1                     :(JMATCH)  
JEWELS_END
                                                
*       Example from the task (prints 3)
        OUTPUT = JEWELS('aA','aAAbbbb')
*       Example with no jewels (prints 0)
        OUTPUT = JEWELS('z','ZZ')
END
Output:
3
0

SQL

-- See how many jewels are among the stones
declare @S varchar(1024) 	=	'AaBbCcAa'
,	@J varchar(1024)	=	'aA';

declare @SLEN	int = len(@S);
declare @JLEN	int = len(@J);
declare @TCNT	int = 0;

declare @SPOS	int = 1;	-- curr position in @S
declare @JPOS	int = 1;	-- curr position in @J
declare @FCHR	char(1);	-- char to find

while @JPOS <= @JLEN
begin

	set @FCHR = substring(@J, @JPOS, 1);

	set @SPOS = 1;

	while @SPOS > 0 and @SPOS <= @SLEN
	begin
		
		set @SPOS = charindex(@FCHR, @S COLLATE Latin1_General_CS_AS, @SPOS);
		
		if @SPOS > 0 begin
			set @TCNT = @TCNT + 1;
			set @SPOS = @SPOS + 1;
		end
	end

	set @JPOS = @JPOS + 1;
end
print 'J='+@J+' S='+@S+' TOTAL = '+cast(@TCNT as varchar(8));
Output:
J=aA S=AaBbCcAa TOTAL = 4

Swift

func countJewels(_ stones: String, _ jewels: String) -> Int {
  return stones.map({ jewels.contains($0) ? 1 : 0 }).reduce(0, +)
}

print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))
Output:
3
0

Tcl

proc shavej {stones jewels} {
    set n 0
    foreach c [split $stones {}] {
        incr n [expr { [string first $c $jewels] >= 0 }]
    }
    return $n
}
puts [shavej aAAbbbb aA]
puts [shavej ZZ z]
Output:
3                                                                                       
0

Terraform

variable "jewels" {
  default = "aA"
}

variable "stones" {
  default = "aAAbbbb"
}

locals {
   jewel_list = split("", var.jewels)
   stone_list = split("", var.stones)
   found_jewels = [for s in local.stone_list: s if contains(local.jewel_list, s)]
}

output "jewel_count" {
  value = length(local.found_jewels)
}
Output:
$ terraform apply --auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

jewel_count = 3

$ TF_VAR_jewels=z TF_VAR_stones=ZZ terraform apply --auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

jewel_count = 0

Transd

#lang transd

MainModule: {
    countJewels: (λ j String() st String() locals: n 0
        (for s in st do 
            (if (contains j s) (+= n 1)))
        (ret n)
    ),
    _start: (λ (lout (countJewels "aA" "aAAbbbb"))
               (lout (countJewels "b" "BB")))
}
Output:
3
0

VBA

Translation of: Phix
Function count_jewels(stones As String, jewels As String) As Integer
    Dim res As Integer: res = 0
    For i = 1 To Len(stones)
        res = res - (InStr(1, jewels, Mid(stones, i, 1), vbBinaryCompare) <> 0)
    Next i
    count_jewels = res
End Function
Public Sub main()
    Debug.Print count_jewels("aAAbbbb", "aA")
    Debug.Print count_jewels("ZZ", "z")
End Sub
Output:
 3 
 0 

Visual Basic .NET

Translation of: C#
Module Module1

    Function Count(stones As String, jewels As String) As Integer
        Dim bag = jewels.ToHashSet
        Return stones.Count(AddressOf bag.Contains)
    End Function

    Sub Main()
        Console.WriteLine(Count("aAAbbbb", "Aa"))
        Console.WriteLine(Count("ZZ", "z"))
    End Sub

End Module
Output:
3
0

Vlang

Translation of: Go
fn js(stones string, jewels string) int {
	mut n := 0
    for b in stones.bytes() {
        if jewels.index_u8(b) >= 0 {
            n++
        }
    }
    return n
}
 
fn main() {
    println(js("aAAbbbb", "aA"))
}
Output:
3

Wren

Translation of: Kotlin
var countJewels = Fn.new { |s, j| s.count { |c| j.contains(c) } }

System.print(countJewels.call("aAAbbbb", "aA"))
System.print(countJewels.call("ZZ", "z"))
Output:
3
0

XPL0

string 0;       \Use zero-terminated strings

func Count(Stones, Jewels);
\Return number of letters in Stones that match letters in Jewels
char Stones, Jewels;
int  Cnt, I, J;
[Cnt:= 0;
I:= 0;
while Jewels(I) do
    [J:= 0;
    while Stones(J) do
        [if Stones(J) = Jewels(I) then Cnt:= Cnt+1;
        J:= J+1;
        ];
    I:= I+1;
    ];
return Cnt;
];

[IntOut(0, Count("aAAbbbb", "aA"));  CrLf(0);
 IntOut(0, Count("ZZ", "z"));  CrLf(0);
 IntOut(0, Count("pack my box with five dozen liquor jugs", "aeiou"));  CrLf(0);
]
Output:
3
0
11

zkl

fcn countJewels(a,b){ a.inCommon(b).len() }
println(countJewels("aAAbbbb", "aA"));
println(countJewels("ZZ", "z"));
Output:
3
0