Wednesday, July 28, 2010

Second largest element in an unsorted array

How will you find out second largest element in an unsorted array?

If you would like to do it in one pass, then have two variables as max, secondMax. Do compare all values with thest values. Initially assign, firstValue as max and secondValue as secondMax do compare them.

Now the next question is, will it scale if you have large stream of numbers and if you would like to find Top N from that large stream of numbers?

Have array withe size N and repeat the above steps.

How to convert Version 1 requests into V2 requests?

Scenerio: If existing application is using lot of  Version 1 requests that need to be converted into version 2 requests.

Solution: Write a wrapper over the existing V1 class. For example if you import some class org.version.Version1 and calling various methods like addHeader(), addData() etc, write a wrapper org.wrapper.Version1Wrapper and define all  methods present in org.version.Version1. Inside org.version.Version1Wrapper  call org.version.Version2 methods. Now do a Search and Replace in all your existing code such that org.version.Version1 should be replaced by org.version.Version1Wrapper. Write a well defined unit test case for the newly written org.version.VersionV1Wrapper class.

Advantages: Very less implementation and testing effort.

Java code to convert base 10 value to a hex value

import org.junit.*;
import static org.junit.Assert.*;
public class HexValue
{
    private static final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
   
    private static String toHexValue(int baseValue) throws IllegalArgumentException
    {
        StringBuilder builder = new StringBuilder();
        if(baseValue < 0)
        {
            throw new IllegalArgumentException("Given base value "+baseValue+" is less than zero");
        }
        else if(baseValue == 0)
        {
            return String.valueOf(0);
        }       
        while(baseValue > 0)
        {
            int mod = baseValue%16;
            builder.insert(0,hexArray[mod]);
            baseValue = baseValue/16;
        }
        return builder.toString();
    }

    @Test public void  testZero()
    {
        assertEquals("0",HexValue.toHexValue(0));
    }
   
    @Test (expected=IllegalArgumentException.class)
    public void  testNegative()
    {
        HexValue.toHexValue(-8);
    }
   
    @Test
    public void  testValidInput()
    {
        assertEquals("A0",HexValue.toHexValue(160));
        assertEquals("100",HexValue.toHexValue(256));
        assertEquals("EA",HexValue.toHexValue(234));
    }
   
   
    public static void main(String a[])
    {
        if(a.length != 1)
        {
            System.out.println("Help:   java HexValue [baseValue]");
            return;
        }
       
        System.out.println("Hexa Decimal value of "+a[0]+" is "+HexValue.toHexValue(Integer.parseInt(a[0])));
    }
}

How to Spam one's personal mail id?

1. Somehow get hold of that person's mail id. You know your own ways of knowing that person's personal mail id.
2. Subscribe that person's mail id to the websites you would like most. Those websites obsivously irritate the victim.
3. If you think that person is blocking your marriage, then subscribe that mail-id to some matrimonial site. You have the privilege of choosing the RIGHT match for your victim. After doing this you will have full satisfaction and inside happiness forever.
4. Subscribe him for some adult jokes web site.
5. As always you can send some actress pictures since sending your pictures could be a waste of time.

Sigh.....

Tuesday, July 27, 2010

A mobile - A Car - A hardware

Can you draw a block diagram for a mobile application that communicates with a Car and a hardware which has legacy C, C++ module?

And here it is ...

Monday, July 26, 2010

Indexing - the Need

Objects are stored in discs just like they are stored in memory. Every object has a memory pointer at which it has been stored. Like wise for example a database row, has a location pointer at which is has been stored in the disc.

As for as the arrays are concerned, if the stored memory is contigeous, it is easy to randomly fetch that element. Let as assume we have an integer array with length 10. In java, integer occupies 4 bytes. We know the startIndex of this array while defining this array. Lets say its 1000. Now if we want to access 4th element, we shall directly go to 1000 + 3 * 4 = 1012 and read next 4 bytes. This is one kind of indexing.

This principle can be applied to database too but with many complexities involved. For example having multiple columns and variable string length etc. If we assume constant maximum length, then we might end up in wasting some space but with the performance benefits.

Normally rows are ordered based on primary key. Hence by default rows are indexed based on primary key. On accesssing the primary key value in the disc, user get to know the location of the complete row and if possible size of that row. If you want a specific column to be searched frequently, we shall index that column. By indexing means here, that values of that column are stored in a sorted manner in a separate place.

Now the users query might be little more complex, like checking whether value 5 exist or not or get the row values when my column value is 5. Here we need to scan through the values of the primary key/indexed column. So here sorting can help us to minimize the retrival time. It helps you find the element in log n time.

Sunday, July 25, 2010

How to improve performance of an application when you know nothing about that?

An application is given to you and now the question is how to improve the performance of that application?

Initially you know nothing about that application. So how do you execute the above task? Its through LEARNING. Learning could come through books, colleagues, google ..... and finally it could come from your own experience too.

Before answering the above question let us define the term performance. Bad performance means the system/application is delivering the output with some glitches. Performance of an application is measured in terms of efficient usage of resources. In other words improving the performance means finding and rectifying the inappropriate usage of resources. At the bottom level, it could end up in identifying and rectifying defects in the application either it could be in the application code or database or any other middle level layers.

Time is an important factor as for as the performance engineering is concerned. Less the time taken for a given task, better the usage of resources. Some times it could end up with using excessive usage of resources too. There should be a well balance between the usage of resources and the performance of the system.

Now what are all the resources used by that application?

1. I/0

File Access, database file access, other storage access, socket read/write and inter process communication etc.

2. CPU

CPU is used heavily for all computational intensive operations.

3. Memory

Memory helps you to reduce I/0 and hence you will get better performance by making
full use of memory.

1. Now identify the set of operations for which the performance is not upto the mark.
2. Prepare right tools to monitor the above resources while performing those operations. For example CPU, memory, IO can be monitored through commands like top in linux. Task Manager in Windows could give us wonderful inputs. Memory Analyzers like OptimizeIt, JProbe could give us wealth of input. Custom tools like sql query analyzer to find repetitive queries and queries that taking longer time will be very handy. In the case of web servers/application servers, tools that are analyzing http headers could help us to identify unncessary requests or repetetive requests.
3. Execute above operations and see the usage of resouces while doing the same.
4. Identify abnormal usages and try to rectify them. For example excessive IO could be rectified by proper caching, efficient usage of algorithms, indexing or even some times replacing default discs with high speed discs like RAID could do.
5. Excessive memory usage could be identified through OptimizeIt or JProbe. They have the capacity of identifying root cause of the excessive object creation. It could be because of the bugs in the application or we can go for object pooling to minimize temporary objects creation.
6. Like wise excessive CPU usage could be avoided by using efficient algorithms or sometimes through parallel processing etc.

At the end, if you get success, you will be a WELLKNOWN from UNKNOWN as for as the application is concerned.

Saturday, July 24, 2010

What does Tiles do?

Tiles helps us to create consistent layouts through out the product/website. For example, consider the scenerio of having one header.jsp/footer.jsp and multiple content.jsp.

Here content.jsp could be changing for each and every request. In simple jsp implementation, we can achieve this by passing content jsp name as request attribute from the action class and dynamically we can include the jsp through jsp scriptlet (<%=request.getAttribute("contentName")%> or through some jstl core tags like c:get.

Now what we need to do if we have multiple header.jsp and footer.jsp. In other words what we will do if we need to show customer specific headers and footers but at the same time we need to maintain consistent L & F through out the product/website. Here comes the real usage of tiles, we will have only one layout.jsp and we will insert different header jsps (say header1.jsp header2.jsp etc) through tiles-def.xml combined with struts forwarding mechanism.

So basically tiles helps us to abstract and decouple layout and implementation jsps.