Skip to content

Instantly share code, notes, and snippets.

@gladimdim
Last active November 11, 2021 12:45
Show Gist options
  • Save gladimdim/53f7c1fd1912a4533ebd55ff8f059c97 to your computer and use it in GitHub Desktop.
Save gladimdim/53f7c1fd1912a4533ebd55ff8f059c97 to your computer and use it in GitHub Desktop.
/// https://www.hackerrank.com/challenges/gem-stones/problem
///
/// There is a collection of rocks where each rock has various minerals embedded in it. Each type of mineral is designated by a lowercase letter in the range .
/// There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in the collection.
///
int calcGemStones(List<String> input) {
var map = {};
// go over the input collection and calculate amount of string where the character is present
// In order not to count "aaa" as three times we maintain ignoreSet set
for (var string in input) {
Set ignoreSet = {};
for (var i = 0; i < string.length; i++) {
if (ignoreSet.contains(string[i])) {
continue;
}
// init in case value is new
map[string[i]] ??= 0;
map[string[i]] += 1;
// remember the character and ignore it in next loops
ignoreSet.add(string[i]);
}
}
var length = input.length;
// if amount of appearances is equal to amount of input strings
// then we found a gem and add +1 to counter
return map.values.fold<int>(0, (previousValue, element) {
if (element == length) {
previousValue++;
}
return previousValue;
});
}
void main() {
var input = ["abc", "bc", "cba"];
print("Gem stones");
print(calcGemStones(input)); // 2
input = ['abcdde', 'baccd', 'eeabg']; // 2
print(calcGemStones(input));
input = ['basdfj', 'asdlkjfdjsa', 'bnafvfnsd', 'oafhdlasd']; // 4
print(calcGemStones(input));
input = ['a', 'b', 'c', 'd']; // 0
print(calcGemStones(input));
input = ['a', 'ab', 'ca', 'dddbbbbbcaccd']; // 1
print(calcGemStones(input));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment