Jewels and stones: Difference between revisions
({{Jewels and Stones}}Added task description.) |
(→{{header|Perl 6}}: Added Perl 6 solution) |
||
Line 60: | Line 60: | ||
0 |
0 |
||
</pre> |
</pre> |
||
=={{header|Perl 6}}== |
|||
<lang perl6>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 }.sum // 0; |
|||
} |
|||
say count-jewels 'aA' , 'aAAbbbb'; |
|||
say count-jewels 'z' , 'ZZ';</lang> |
|||
{{Out}} |
|||
<pre>3 |
|||
0</pre> |
|||
=={{header|Ring}}== |
=={{header|Ring}}== |
Revision as of 13:27, 25 April 2018
- 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. A lower case letter is considered to be different to its upper case equivalent for this purpose i.e. 'a' != 'A'.
2. The parameters do not need to have exactly the same names.
3. 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.
C
<lang c>#include <stdio.h>
- include <string.h>
int count_jewels(const char *s, const char *j) {
int i, count = 0; for (i = 0; i < strlen(s); ++i) if (strchr(j, s[i])) ++count; return count;
}
int main() {
printf("%d\n", count_jewels("aAAbbbb", "aA")); printf("%d\n", count_jewels("ZZ", "z")); return 0;
}</lang>
- Output:
3 0
Kotlin
<lang scala>// 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"))
}</lang>
- Output:
3 0
Perl 6
<lang perl6>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 }.sum // 0;
}
say count-jewels 'aA' , 'aAAbbbb'; say count-jewels 'z' , 'ZZ';</lang>
- Output:
3 0
Ring
<lang ring>
- Project Jewels and Stones
- Date 2018/04/25
- Author Gal Zsolt (~ CalmoSoft ~)
- Email <calmosoft@gmail.com>
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
</lang> Output:
3 0