Tags

May 29, 2012

How to print multi-digit numbers like a 7-segment display

During an interview , many interviewers like to ask very simple coding questions. This is usually to check how fast the interviewee can do a context switch in her mind, her ability to think about some very basic problem, etc.
So, let’s tackle a few of such coding problems in this post. I am using Java as the programming language in this example,

The idea was to help some people which started preparing for interview. I hope you find some value in it.

This is simple java program to display number in 7 segment format

Example :123 should be display in following format, and in one line.
_ _
| _| _|
| |_ _|

1 - Set up your initial data for each number. You could do this as a 2d array (dimension 1: digit, dimension 2: line)
For example:
numbers[0][0] = "|-|"
numbers[0][1] = "| |"
numbers[0][2] = "|_|"

numbers[1][0] = "  |"
numbers[1][1] = "  |"
numbers[1][2] = "  |"

2 - For each line that makes up the character, scan across each digit in your input and write the appropriate string. This will build up the characters line by line.
        public class DigitalDisplay {
            /**
             * @param args
             */
        public static void main(String[] args) {
        String [][] num=new String[4][3];
        num[0][0]="|-|";  //this will display complete "0"
        num[0][1]="| |";
        num[0][2]="|_|";

        num[1][0]=" |";
        num[1][1]=" |";
        num[1][2]=" |";

        num[2][0]=" -|";
        num[2][1]=" _|";
        num[2][2]=" |_";

        num[3][0]=" -|";
        num[3][1]=" _|";
        num[3][2]=" _|";
        int[] input = {2,1,3}; 
        for (int line = 0; line < 3; line++)
        {          
            for (int inputI=0; inputI < input.length; inputI++)
            {
                int value = input[inputI];
                System.out.print(num[value][line]);
                System.out.print("  ");
            }          
            System.out.println();
        }
    }
}

**OUTPUT**

 -|   |   -|  
 _|   |   _|  
 |_   |   _|  

Feb 23, 2012

How to add ellipsis (…) into HTML tag if content too wide


1>Add following jquery script




2>Add following style in style tag


3>Add div tag for which you want to apply eclipse also specify class as “ellipsis”
Hi hi hi hh ihi hiih ihi i hi hihi hi hh h h h

4> Add following code into script tag to apply ellipsis

Feb 22, 2012

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.

Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.

Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.
Map map = new HashMap();

//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration and is more clean.

Method #3: Iterating using Iterator.

Map map = new HashMap();
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
f you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

Check if one string is a rotation of other string

Two string s1 and s2 how will you check if s1 is a rotated version of s2

For Example:
if s1=avs then the following are some of its rotated versions:
vsa
sav
vas
where as "vas" is not a rotated version.
algorithm checkRotation(string s1, string s2) 
  if( len(s1) != len(s2))
    return false
  if( substring(s2,concat(s1,s1))
    return true
  return false
end
In Java:
boolean isRotation(String s1,String s2) {
    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

Create a custom exception in Java

Following are the steps to create custom exception.

(1) create a custom exception class in Java;
(2) throw our custom Java exception;
(3) catch our custom exception; and
(4) look at the output from our custom exception when we print a stack trace.

To create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:
/**
 * My custom exception class.
 */
class CustomException extends Exception
{
  public CustomException(String message)
  {
    super(message);
  }
}

A method to throw our custom Java exception



here's a small example class with a method named getUser that will throw our custom exception (CustomException) if the method is given the value of zero as a parameter.

/**
 * Our test class to demonstrate our custom exception.
 */
class User
{
  public String getUser(int i) throws CustomException
  {
    if (i == 0)
    {
      // throw our custom exception
      throw new CustomException("zero ...");
    }
    else
    {
      return "user";
    }
  }
}

To test our custom Java exception. In our main method, we'll create a new instance of our User class, then call the getUser method with the value of zero, which makes that method throw our custom Java exception:

/**
 * A class to test (throw) the custom exception we've created.
 *
 */
public class CustomExceptionExample
{
  public static void main(String[] args)
  {
    // create a new User
    User user= new User();
    
    try
    {
      // intentionally throw our custom exception by
      // calling getUser with a zero
      String userStr= user.getUser(0);
    }
    catch (CustomException e)
    {
      // print the stack trace
      e.printStackTrace();
    }
  }
}