HackerRank Gem Stones

// September 5th, 2014 // HackerRank Solutions

https://www.hackerrank.com/challenges/gem-stones

John has discovered various rocks. Each rock is composed of various elements, and each element is represented by a lowercase latin letter from ‘a’ to ‘z’. An element can be present multiple times in a rock. An element is called a ‘gem-element’ if it occurs at least once in each of the rocks.

Given the list of N rocks with their compositions, display the number of gem-elements that exist in those rocks.

Input Format
The first line consists of N, the number of rocks.
Each of the next N lines contain rocks’ composition. Each composition consists of lowercase letters of English alphabet.

Output Format
Print the number of gem-elements that are common in these rocks.

Constraints
1 ≤ N ≤ 100
Each composition consists of only small latin letters (‘a’-‘z’).
1 ≤ Length of each composition ≤ 100

My Solution 60/60


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace GemStones
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberOfStones = int.Parse(Console.ReadLine());
            if (numberOfStones >= 1 && numberOfStones <= 100)
            {
                string[] stoneComps = new string[numberOfStones];
                Regex tmpReg = new System.Text.RegularExpressions.Regex("^[a-z]{1,100}$");
                char[] result = "abcdefghijklmnopqrstuvwxyz".ToCharArray();

                for (int i = 0; i < numberOfStones; i++)
                {
                    string tmpInput = Console.ReadLine();
                    if (tmpReg.Match(tmpInput).Value != tmpInput)
                        throw new FormatException("Invalid string input!");
                    result = CompareGem(result, tmpInput);
                }

                Console.WriteLine(result.Length);
            }
            else
                throw new ArgumentOutOfRangeException("Value must be between 1 and 100");
        }

        private static char[] CompareGem(char[] result, string p)
        {
            List<char> newResult = new List<char>();
            foreach (char tmpChar in p.ToCharArray())
                if (result.Contains(tmpChar) && !newResult.Contains(tmpChar))
                    newResult.Add(tmpChar);

            return newResult.ToArray();
        }
    }
}
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt