Gemstones

My wife is out with a friend shopping. She is expected back around 11:00 AM. At that time will start preparing lunch.

I took a look at the next Hacker Rank challenge for strings in Java. If interested you may find the description here.

It seems like John (pure coincidence) has a set of rocks. Rocks may have different minerals. For some reason if any mineral is present in all rocks then they become a gem. Not sure how they arrived to such conclusion. A set of coal piles is still coal, not a gem. Notwithstanding my last comment; your mission, if you do accept, is to find how many gems are in John’s sets of rocks.

Seems like we need to find the count of which characters representing minerals are found in all the strings representing the rocks. I decided to preserve the metaphor in my solution which follows:

   // Complete the gemstones function below.
    static int gemstones(String[] arr) {

    	final String minerals = "abcdefghijklmnopqrstuvwxyz";
    	
    	int gems = 0;
    	
    	// **** loop through the minerals ****
    	for (int i = 0; i < minerals.length(); i++) {
    		
  			// **** get the current mineral ****
			char mineral = minerals.charAt(i);
			
    		// **** loop through the rocks (arr) looking for this mineral ****
    		int mineralInRock = 0;
    		for (int j = 0; j < arr.length; j++) {
    			
    			// **** check if this mineral is in this rock ****
    			if (arr[j].indexOf(mineral) != -1)
    				mineralInRock++;
    		}
    		
    		// **** count this gem (if found in all rocks) ****
    		if (mineralInRock == arr.length)
    			gems++;
    	}    	

    	// **** total number of gems ****
    	return gems;
    }

The code passed the battery of tests and was accepted.

If you wish to see the entire code, you may find it in my GitHub repository.

As usual, if you have a comment or question in this post or any other post in my blog, please do not hesitate and leave me a note.

Keep on learning, experimenting and having fun;

John

Please follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.