Saturday, August 25, 2012

Re-blogging my experience on this really cool blog.

The other day, I was going through some JDK code to understand what was happening under the hood. I saw this code in a couple of places. (such as binary search and merge sort) I really couldn't figure out why someone would want to use the unsigned right shift operator to do simple division.
mid = low + high >>> 1;
mid = low + high / 2
instead of this,

Until I recently came across this post from Peter Norvig in this blog Google Research Blog This bug must have been fixed by Josh Bloch I guess. Since he seems to be the author of the classes which I was checking.
A small side note here, I too fell into the trap of thinking this was done for performance issues. However the blog clearly states the root cause was something more sinister. Love to be in a place where your code get's pushed to the limit. I guess scale is an awesome beast to deal with.
When will my day arrive :-(. When millions use my code.

Sunday, August 12, 2012

Simple stuff in java that I learnt today

Coming from a C background I never really got to write code in java to do some string processing. The other day I was doing some simple stuff in java and I hit these problems.
  1. Converting a string to an integer array: It came as a shocker when I couldn't get this to work right away. However a quick google search gave me a whole bunch of answers. I have written the method below:
      public int[] getIntArrayFromString(String s) {
      int[] result = new int[s.length()];
      for(int i =0; i < s.length(); i++) 
        result[i] = Character.digit(s.charAt(i));
      return result;
    }
    
    The Character wrapper class comes to rescue here. However the logic for digit is pretty similar to C logic. Where the char ASCII vale is taken and subtracted from ASCII value of One '1'.
  2. Reversing a string:
    Again using String Buffer to do this is the best method possible.One from the front and the other from the rear.
     
      public static String revertString(String msg) {
          StringBuffer sb = new StringBuffer();
          for(int i=msg.length() - 1, i >= 0; i++ )
              sb.append(msg.charAt(i));
          return sb.toString();
      }
    
Super simple stuff wanted to see if my coding tags work.