Labels

Showing posts with label Puzzles/Algorithms. Show all posts
Showing posts with label Puzzles/Algorithms. Show all posts

Monday, February 14, 2011

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.

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])));
    }
}

Monday, April 12, 2010

Missing Number

In a table you have 99999 rows. But the max id is 100000. That means only one row is missing. How will you find that missing id in one simple query?

















select (max(id)*(max(id)+1))/2 - sum(id) from table;

Math: to find sum of n integers, you can use n*n+1/2.