Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Do intersect of all characters of strings comming as the input.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class GemStones { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int rocks = scanner.nextInt(); char[] first = scanner.next().toCharArray(); Set<Character> result = new HashSet<>(); for (char c : first) { result.add(c); } for (int i = 1; i < rocks; i++) { char[] composition = scanner.next().toCharArray(); Set<Character> set = new HashSet<>(); for (char d : result) { for (int j = 0; j < composition.length; j++) { if(d == composition[j]) { set.add(composition[j]); } } } result = set; } System.out.println(result.size()); scanner.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
function processData(input) { var lines = input.split('\n'); var first = lines[1].split(''); for(var i = 2; i < lines.length; i++) { first = intersect(first, lines[i].split('')); } console.log(first.length) } function intersect(arr1, arr2) { var unique1 = arr1.distinct(); var unique2 = arr2.distinct(); return unique1.distinct().filter(function(s) { return unique2.distinct().indexOf(s) !== -1 }); } Array.prototype.distinct = function() { var hash = {}; var a = []; for(var i = 0; i < this.length; i++) { if(hash.hasOwnProperty(this[i])) { continue; } hash[this[i]] = true; a.push(this[i]); } return a; }; process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Ruby
1 2 3 4 5 6 7 |
string_count = gets.to_i first = gets.chars.uniq (string_count - 1).times do s = gets.chars.uniq first = first & s end puts first.length |
Scala
1 2 3 4 5 6 7 8 9 |
import scala.io.Source object Gemstones extends App { val strings = Source.stdin.getLines().drop(1).toList val first = strings(0) val gemstones = strings.drop(1).foldLeft(first)(_ intersect _) println(gemstones.size) } |