Funny String

It is Sunday in the Twin Cities of Minneapolis and St. Paul and it is starting to snow. The forecast calls for snow turning into rain. Later this morning my wife and I are going to the Mall of America (MOA) for a walk. It beats getting on exercise equipment at home and watching TV.

I selected the Funny String practice from HackerRank. Given a string one has to reverse the characters and place them in a second string. Then traverse both comparing the absolute differences among consecutive characters. If the differences match then the function should return the string “Funny”; otherwise it should return “Not Funny”.

As usual I try to develop a simple and well documented function.

The code for the function follows:

	// Complete the funnyString function below.
    static String funnyString(String s) {

    	// **** r holds the reverse of s ****
    	String r = new StringBuilder(s).reverse().toString();
    	
    	// **** build associated arrays with byte values ****
    	byte[] sba = s.getBytes();
    	byte[] rba = r.getBytes();
    	
    	// **** compare the values of the adjacent bytes ****
    	for (int i = 0; i < (sba.length - 1); i++) { // **** difference in sba **** int sbaDiff; if (sba[i] > sba[i + 1]) {
    			sbaDiff = sba[i] - sba[i + 1];
    		} else {
    			sbaDiff = sba[i + 1] - sba[i];
    		}
    		
     		// **** difference in rba ****
    		int rbaDiff;
    		if (rba[i] > rba[i + 1]) {
    			rbaDiff = rba[i] - rba[i + 1];
    		} else {
    			rbaDiff = rba[i + 1] - rba[i];
    		}
    		
    		// **** check if they do NOT match ****
    		if (sbaDiff != rbaDiff)
    			return "Not Funny";
    	}
 
    	// **** differences match ****
    	return "Funny";
    }

If you are interested in taking a look at the entire solution, you may find it in my GitHub repository.

As usual, if you have comments or questions regarding this or any other post in this blog, please leave me a comment bellow.

Keep on learning, practicing 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.