Tuesday, April 26, 2011

Tricky Java question: finding the missing number

So here is the detailed question:
Question (1): Suppose a number is missing in a jumbled sequence of 1 to 100. So, find the missing number. So the series may look like this:
{2,4,1,100,67.....}

Solution: Sum of natural numbers is = n*(n+1)/2. So we will find the sum of the series we have and subtract it from the sum of natural numbers from 1 .. 100 and that's how we got the missing number. To illustrate the logic we will take a list of only 10 numbers.
public class FindOneMissingNumber {
public static void main(String[] args) {
// in the below jumbles series of 1-10, 7 is missing
int [] arr = {9,4,5,1,10,2,6,3,8};

// Sum of numbers till 10
int sumNaturalNumbers = 10 *(10+1)/2;
int sumOurSeries=0;
for(int i=0;i<arr.length;i++){
sumOurSeries +=arr[i];
}
System.out.println("Sum of our series: "+sumOurSeries);
System.out.println("missing number= "+(sumNaturalNumbers-sumOurSeries));
}
}


Now let us make the situation more complicated. Suppose we do not know how many numbers are missing in the series it can be 2, 3, 4 or just any number of digits missing. How to figure out which digits are missing.

Here is the solution, see if you can figure out apart from these:
Solution (1)
Approach:
  1. Create a new array b[] of the size of missing numbers array a[] +number of digits missing
  2. copy the numbers from first array into second array so that b[a[i-1]] = a[i]
  3. Now search the second array to see which field is contains zero
  4. Missing fields = array positions having zero + 1

Code listing:
/**
*
* @author Dharmvir Singh
* Solution has the complexity as O(n)
*/
public class FindOneMissingNum {
public static void main(String[] args) {
// two numbers are missing: 2, 6, 10
int a [] = {3,5,7,1,4,8,9};
int countOfMissingDigits=3;
int b [] = new int [a.length+countOfMissingDigits];
for (int i = 0; i < a.length; i++) {
b[(a[i]-1)]=a[i];
}
for (int i = 0; i < b.length; i++) {
if(b[i]==0){
System.out.println("missing number is"+(i+1));
}
}
}

}

SO the question in the comments can be solved either by the solution given above or there is one more solution. This solution also has the complexity O(n).
So here is the solution:
Approach:
  1. Suppose series is a[]={4,2,3,1,2}. Suppose positions here are starting from i= o to 4
  2. Start marking the numbers at positions a[a[i]-1] as negative.
  3. In above process exclude all the numbers which are already marked negative(-)
  4. All the positions will have their numbers marked (-) except the positions representing the missing number
Code listing:
public class FindMissingNum {

 /**
  * @param args
  */
 public static void main(String[] args) {

  // two numbers are missing: 2, 6
  int a[] = { 3, 5, 1, 7, 1, 3, 4, 8, 7, 9 };
  int t1, t;
  for (int i = 0; i < a.length; i++) {
   t = a[i];
   // if t is already negative then make it positive as
   // positions cannot be negative
   if (t < 0) {
    t1 = -t;
    if (a[t1 - 1] > 0)
     a[t1 - 1] = -a[t1 - 1];
   } else {
    if (a[t - 1] > 0)
     a[t - 1] = -a[t - 1];
   }

  }
  // Print the missing numbers
  for (int i = 0; i < a.length; i++) {
   if (a[i] > 0) {
    System.out.println("Missing Number:" + (i + 1));
   }
  }
 }
}

Related posts on this blog:
Checking if i=4or5or6 without using any logical operator like && or ||

Monday, April 25, 2011

Memory Structure in JVM

JVM has various Runtime data areas some of which are created at the startup of JVM and are destroyed at the shutdown of JVM. Remaining data areas are per-thread.
Figure below explains the Runtime data areas that JVM has:

JVM has only two Runtime memory area types.:
  1. Heap
  2. Non-Heap
    1. PC register
    2. JVM stack
Let us explore every Memory Area one by one.
  1. JVM Heap:
    1. shared across all the Threads
    2. Created on JVM start-up
    3. Memory is reclaimed using the Garbage Collection.
    4. Heap can be of fixed size or dynamically expandable. Users can expand the memory between permissible limits.
    5. If JVM Heap is configured for dynamic expansion and sufficient memory is not available then JVM will throw OutOfMemoryError Error
  2. PC(program Counter) Register: PC is created per Thread. At one time, it executes code of one method for the associated thread.
    1. If that method is not native, It contains the address of the JVM instruction currently being executed.
    2. If the method currently being executed by the thread is native, the value of the Java virtual machine's pc register is undefined.
  3. JVM stack: Each JVM thread has a private Java virtual machine stack, created at the same time as the thread
    1. It stores frames.frames
    2. Stacks are similar to conventional language(example,) stacks
    3. These store local variables, partial results and plays part in method invocation and return
    4. Size of JVM stack can be fix or expandable. If the size is fixed and for some operation memory required is more than the size then JVM throws StackOverFlowError. If Stack size is dynamically expandable and now if the required memory is more then the available then JVM will throw OutOfMemoryError Error
  4. Method Area: It is shared among all Java virtual machine threads.It is created on virtual machine start-up.
    1. It stores per-class structures such as the runtime constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface type initialization
    2. It is logically part of the heap but Specification doesn't restrict this.So it can be independent part also
    3. if JVM runs short of Method Area memory for a request then OutOfMemoryError Error will be thrown.
  5. Runtime Constant Pool: Runtime constant Pool memory is allocated from the Method Area. The runtime constant pool for a class or interface is constructed when the class or interface is created by the Java virtual machine.
    1. It is a per-class or per-interface runtime representation of the constant_pool table in a class file. Similar to symbol table in conventional languages
    2. It stores different kinds of constants, ranging from numeric literals known at compile time to method and field references that must be resolved at run time.
  6. Native Method Stacks: These stacks are provided by JVMs that support native methods (methods written in languages other than Java). They are created per thread.
Discussing about JVM stacks I mentioned about Frames. Lets discuss them now. Frames A frame is used to store data and partial results, as well as to perform dynamic linking , return values for methods, and dispatch exceptions.A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt.Each frame has its own array of local variables , its own operand stack (§3.6.2), and a reference to the runtime constant pool of the class of the current method. The memory of these frames is determined at compile time and allocated when the method is actually invoked at runtime. Frames have again three parts:
  1. Local variables's stack
  2. Operand stack
  3. Frame Data
So, If we summarise
  • Instance variables are stored in Heap
  • Local variables are stored on stack
  • Static variables are stored in Method Area
  • Arrays are stored on heap
Now take a look at the diagram below to make things more clear: original source of above image Now finally references:

Wednesday, April 20, 2011

Checking if i=4 or 5 or 6 in single if condition without using logical operators

I tried and found two solutions. One is mathematical and other one is just a java trick.

Mathematical solution:


public class Test1 {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
if((i-4)*(i-5)*(i-6) == 0 ){
System.out.println("4<=i<=6");
}else{
System.out.println("i!=4or5or6");
}
}
}


Other solution is bit tricky:


public class Test2 {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
if("4,5,6".indexOf(String.valueOf(i)) >=0){
System.out.println("4<=i<=6");
}else{
System.out.println("i!=4or5or6");
}
}
}

Sunday, April 10, 2011

HIbernate composite Primary Key

Strategy:
We have to create a separate class to represent the composite primary key and the fields that represent the primary key has to be moved to the new class.

So suppose We have a class called as Contact1 with following fields
ContactId // primary key field
EmailId // primary key fields
firstName
and LastName

So we will create a new class called ContactPK with two fields
ContactId // primary key field
EmailId // primary key fields

and Our Contact1 class will have following fields
firstName
and LastName

rest all is just simple.

We will look at how to do select operation and insert operation here.

Code for Contact1 is as follows:

package blog.javaespresso.tut.hibernate.compositekey;

import java.io.Serializable;

public class ContactPK implements Serializable{
private String email;
private long id;

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

}


Code for ContactPK class:


package blog.javaespresso.tut.hibernate.compositekey;

public class Contact1 {
private String firstName;
private String lastName;
private ContactPK contactPK;

public ContactPK getContactPK() {
return contactPK;
}

public void setContactPK(ContactPK contactPK) {
this.contactPK = contactPK;
}

/**
* @return First Name
*/
public String getFirstName() {
return firstName;
}

/**
* @return Last name
*/
public String getLastName() {
return lastName;
}


/**
* @param string
* Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}

/**
* @param string
* sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}
}


Hibernate mapping file (Contact1.hbm.xml)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="blog.javaespresso.tut.hibernate.compositekey.Contact1" table="CONTACT1">
<composite-id name="contactPK"
class="blog.javaespresso.tut.hibernate.compositekey.ContactPK">
<key-property name="id" column="ID" type="long">
</key-property>
<key-property name="email" column="EMAIL" type="string">
</key-property>
</composite-id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME" />
</property>
</class>
</hibernate-mapping>


Hibernate config file (Hibernate.cfg.xml): add the mapping file entry

<mapping resource="blog/javaespresso/tut/hibernate/compositekey/contact1.hbm.xml" />


Below is the structure of the project :




Class code to test the insert operation:


package blog.javaespresso.tut.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import blog.javaespresso.tut.hibernate.compositekey.*;
public class TestInsertCompositeKey {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Contact1 contact = new Contact1();
ContactPK contactPK = new ContactPK();
contactPK.setEmail("holyshit@yahoo.com");
contactPK.setId(1);
contact.setContactPK(contactPK);
contact.setFirstName("holy");
contact.setLastName("shit");
Transaction transaction = session.beginTransaction();
session.save(contact);
transaction.commit();
System.out.println("Inserting Done!");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}finally{
session.flush();
session.close();
}
}
}


Class code to test the select operation:


package blog.javaespresso.tut.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import blog.javaespresso.tut.hibernate.compositekey.Contact1;
import blog.javaespresso.tut.hibernate.compositekey.ContactPK;
public class TestSelectComposite {
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
System.out.println("ftching Record");
ContactPK contactPK = new ContactPK();
contactPK.setEmail("deepak_38@yahoo.com");
contactPK.setId(1);
Contact1 contact1 = new Contact1();
session.load(contact1, contactPK);
System.out.println(contact1.getFirstName());
System.out.println(contact1.getLastName());
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
session.close();http://www.blogger.com/img/blank.gif

}
http://www.blogger.com/img/blank.gif
}
}


Links to eclipse source code and the library files:
sourceCode



Library Files

Wednesday, April 6, 2011

Adding Favicon to your Page

I will cover a few learning I had after I wasted a lot amount of time figuring out how to make favicon work in my application. I struggled with IE for loading my favicon while other browsers it worked well.

Few things you should keep in mind about adding favicon:
0. Image should be 16x16. The image format support by browser vary over the browser and their versions. Here is the Wiki link that can give more details.
http://en.wikipedia.org/wiki/Favicon

1. Make sure the file is a valid icon file. If you are not sure use online icon file generators.

2. Name the file exactly as "favicon.ico". Ignore the double quotes here. they are only to highlight.

3. Issues with IE8 especially:
A. IE8 will never display the icon if the file is on your hard disk. It has
to be on the internet.
B. IE8 will not show the icon if u do not have the www in your url address. So
a - http://yoursitename.com will not work.
b - http://www.yousitename.com will work.

C. IE8 downloads the favicon.ico file in the folder.
C:\Documents and Settings\user\Local Settings\Temporary Internet Files where
user = the name with which u logged in windos xp. In case of Vista/Win. 7
path could be different.
4. This method works if you simply place a valid icon file named favicon.ico in the root directory of you site. OR (follow point number 5)

5. Add these lines into the head part of your html page.
<link rel="icon" href="http://www.MyURL.com/favicon.ico" type="image/x-icon">
<link rel="address bar icon" href="http://www.MyURL.com/favicon.ico">

ideally any should work but didn't work for me so I added both.
6. I have tested the above code with firefox 3.6/4.0 Beta , IE8 and Chrome and it worked.

Thanks and Have hassle free coding.

During my struggle, I found this link to be very useful.

http://social.msdn.microsoft.com/Forums/en/iewebdevelopment/thread/a6fb09ef-aa3e-4e9e-be44-edbfad322657
http://jeffcode.blogspot.com/2007/12/why-doesnt-favicon-for-my-site-appear.html
Please do post your comments to let me know the quality of the article.