Friday, January 16, 2015

Implementation of Binary Search Tree

As mentioned in previous post Binary Search Tree is an important data structure to programmers, developers. It has following important features.

  1. All the values of nodes in the left sub-tree are less than the value in the root node.
  2. All the values of nodes in the right sub-tree are greater than the root node. 
  3. The left and right sub-trees are also binary search trees
  4. There mustn't  be any duplicate node.
A node implementation
    
public class TreeNode { 
 int value;
 TreeNode left;
 TreeNode right;
 
 public TreeNode(int val){
  value = val;
  left = null;
  right = null;
 }
 
 public TreeNode(){
  value = 0;
  left = null;
  right = null;
 }
 
 public void setLeft(TreeNode node){
  left=node;
 }
 
 public void setRight(TreeNode node){
  right=node;
 }
 
 public void setValue(int val){
  value = val;
 }
 
 public int getValue(){
  return value;  
 }
 
 public TreeNode getLeft(){
  return left;
 }
 
 public TreeNode getRight(){
  return right;
 }
}


set methods and get methods are implemented because they are helpful to implement binary search tree using class "TreeNode".

Here's the implementation for Binary Search Tree using "TreeNode" class

public class BST { 

 private TreeNode root; 

 public BST(){
  root = null;
 } 

 /*method to determine whether BST is empty or not*/
 public boolean isEmpty(){
  return root==null;
 } 

 /*method to insert a node to BST*/
 public void insert(int data){
  root=insert(root,data);
 } 

 private TreeNode insert(TreeNode node,int data){
  if(node==null){
   node = new TreeNode(data);
  }
  else{
   if(data<node.getValue())
    node.left=insert(node.left,data);
   else
    node.right=insert(node.right,data);
  }
  return node;
 } 

 /*method to delete a node from BST*/
 public void delete(int val){
  if(isEmpty()){
    System.out.println("Tree Empty");
  }
  else if(!search(val))
   System.out.println("Sorry "+ val +" is not present");
  else{
   root=delete(root,val);
    System.out.println(val+ " deleted from the tree");
  }
 } 

 private TreeNode delete(TreeNode node,int val){
  TreeNode n1,n2,k;  

  if(root.getValue()==val){
   TreeNode lt=root.getLeft();
   TreeNode rt=root.getRight();   

   if(lt==null&&rt==null)
    return null;
   else if(lt==null)
    return rt;
   else if (rt==null)
    return lt;
   else{
    n1=rt;
    n2=rt;
    while(n2.getLeft()!=null)
     n2=n2.getLeft();
    n2.setLeft(lt);
    return n1;
   }
  }

  if(val<root.getValue()){
   k=delete(root.getLeft(),val);
   root.setLeft(k);
  }
  else{
   k=delete(root.getRight(),val);
   root.setRight(k);
  }
  return root;  
 } 

 /*method to count number of nodes of BST*/
 public int countNodes(){
  return countNodes(root);
 } 

 private int countNodes(TreeNode node){
  if(node==null)
   return 0;
  else{
   int count=1;
   count+=countNodes(node.getLeft());
   count+=countNodes(node.getRight());
   return count;
  }
 } 

 /*method to search element of BST*/
 public boolean search(int val){
  return search(root,val);
 } 

 private boolean search(TreeNode node,int val){
  boolean found=false;
  while(node!=null && !found){
   if(val<node.getValue())
    node=node.getLeft();
   else if (val>node.getValue())
    node=node.getRight();
   else{
    found=true;
    break;
   }
   found=search(node,val);  
  }
  return found;
 }
}

In this implementation insert, delete, search, methods are also implemented to insert, delete, search data in BST. This BST is implemented only for integer data but remember we can implement Binary Search tree as compatible with any data type using java generics.

How to insert data to Binary Search Tree (BST)

Binary search tree is one of most important data structure in programming.So lets see how to work with a binary search tree manually.
Main property of a binary search tree is all of the values in the left sub-tree are less than the value in the root and all of the values in the right sub-tree are greater than the root. 

when we enter a data set to a binary search tree.first value goes to the root.If next value is greater than root it is the right child of root. If next value is less than root it is the left child of root.

Lets enter this data set in to a binary search tree.
{ 8, 3, 6, 10, 1, 4, 7, 14, 13}

8 is the root of this BST. 3 is the left child of 8 (root) because 3 is less than 8. 10 is the right child of the 8 (root) because  10 is greater than 8. Next element of the array is 1. 1 goes to left sub-tree of 8 because 1 is less than 8 and it is the left child of the 3 because 1 is less than 3. So on after completing the BST it will looks like this.



Lets try another exercise.
{ 50, 72, 54, 17, 12, 23, 19, 14, 76, 9, 54, 67}
After entering this data set into BST it will look like this




Thursday, January 15, 2015

fastest ways to determine primary numbers in java

For some of programs and for some programming exercises, we need to  determine whether a number is a primary number or not. That is very simple right... even newbies to programming can come up with a solution with java.
But when we are working with large number of numbers,we need more efficient piece of code. Here is some efficient piece of codes found on programming question and answer sites.

       public static boolean isPrime2(int n) {
            if (n <= 1) 
                return false;            
            if (n == 2) 
                return true;            
            if (n % 2 == 0) 
                return false;            
            for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
                if (n % i == 0)
                    return false;                
            }
            return true;
        }

still we can do some improvements to this code
boolean isPrime(long n) {
    if(n < 2) return false;
    if(n == 2 || n == 3) return true;
    if(n%2 == 0 || n%3 == 0) return false;
    long sqrtN = (long)Math.sqrt(n)+1;
    for(long i = 6L; i <= sqrtN; i += 6) {
        if(n%(i-1) == 0 || n%(i+1) == 0) return false;
    }
    return true;
}

and some elegant answers are also there(this is much slower than others)...

    public static boolean isPrime(int n) {
         return !new String(new char[n]).matches(".?|(..+?)\\1+");

But the tricks needed to achieve speed usually sacrifices elegancy.
So,there are lot of new,efficient,elegant algorithms to everywhere. find out, enjoy.. stay with LETS SEE to see more.. :)

Wednesday, January 14, 2015

Remove duplicate elements from an array in Java


In many programming problems we need to remove duplicate elements from an array.In this tutorial lets see how to remove duplicates from an array in java.

  public static int[] remove_duplicates(int[] a){
  int comp,n,numOfRepeats=0;

  for(int i=0;i<a.length;i++){
   n=0;
   comp=a[i];
   for(int j=0;j<a.length;j++){
    if(comp==a[j]&&(i!=j)){
     numOfRepeats++; 
    }
   }
  }

  int sol[]=new int[(a.length-numOfRepeats)];

  int solIndex=0;

  for(int i=0;i<a.length;i++){
   n=0;
   comp=a[i];
   for(int j=0;j<a.length;j++){
    if(comp==a[j]&&(j!=i)){
     n=2;
     break;
    }
   }
   if(n==0){
    sol[solIndex]=comp;
    solIndex++;
   }
  }
  return sol;
 }


The above code is a simple code that any one can imagine. But it may not be very efficient in some cases.
   In java there are lot of built in classes to make this kind of things easy. By using java collection we can create a method as follows.


  public static Integer[] removeDuplicates(Integer[] arr) {

  return new HashSet<Integer>(Arrays.asList(arr)).toArray(new Integer[0]);

}


you can explore more about duplicate removing algorithms using this link..

Monday, January 12, 2015

Repair GRUB2 When Ubuntu Won't Boot

If you have a dual boot system in your computer and if you have installed windows after ubuntu you may not able to log in to ubutnu because you MBR might be changed or overwritten.
Ubuntu and many other linux distributions use the GRUB2 boot loader. In that case you have to restore GRUB2 from a ubuntu live CD or USB drive.
There are two main methods to do this. One is Boot Repair graphical tool that can repair GRUB2 with single click. But i think most suitable way for most cases is use ubuntu terminal to restore GRUB2.

lest see how to restore the GRUB2
first you'll need to boot from a live CD or USB drive. Make sure that version of ubuntu in your live CD or USB drive is the same as the version of ubuntu installed on your computer.  As a example if you have installed ubuntu 14.04 you have to use live CD of ubuntu 14.04.

then open a terminal after booting in to the live environment. Use sudo fdisk -l command to identify the partition ubuntu is installed.

Then Use the following command to mount the ubuntu partition at /mnt

sudo mount /dev/sdX# /mnt

you should replace sdX# part with the device name of your ubuntu partition.
as a example, if the ubuntu installed partition is 'sda6' the command should be  'sudo mount /dev/sda6 /mnt'

Important: if you have a separate boot partition, skip the above command and mount the boot partition at /mnt/boot. if you don't know weather you have a separate boot partition , you probably don't.

Then use the following command to reinstall the GRUB2 from the live CD or USB drive, replacing the dev/sdX with the device name of the hard disk above.Omit the number.
for example if you used /dev/sda6 above use /dev/sda here.

sudo grub-install --boot-directory=/mnt/boot /dev/sdX

Finally restart your computer.
now ubuntu GRUB should be displayed and ubuntu should boot properly.


Saturday, January 10, 2015

Add a syntax highlighter to your blog

If you are doing a blog about programming or some other stuff some times you need to put some code (e.g Java, PHP)in your blog post. so it would be very nice and easy to reader if that code segment is syntax highlighted.

So lets see how to add a syntax highlighter to your blog.

1. First you have to take a backup of your  blog template ( to use if something goes wrong).
2. Then click on 'Template' in the right side of the  page and click on "Edit HTML"(shown in the picture below).


3. After opening the blogger template copy the all CSS given in this link before </b:skin> tag.
4. Then you have to paste the following code before </head> tag.


   <script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

5. Then paste the following code before </body> tag.
<script language='javascript'>

dp.SyntaxHighlighter.BloggerMode();

dp.SyntaxHighlighter.HighlightAll('code');

</script>

6. Finally save the blogger template.
7. Now the syntax highlighter is ready for your page and your codes that syntax highlighting is needed should goes with in <pre></pre> tags as shown below.(code should be entered in HTML mode)

<pre name="code">
...Your html-escaped code goes here...
</pre>

<pre name="code" class="php">
    echo "I like PHP";
</pre>

This code will look like this,

...Your html-escaped code goes here...
    echo "I like PHP";

8. Here is list of supported language for <class> attribute.
9.If you want you can escape your code here 

now you can have a nice syntax highlighter for your blog

Saturday, January 3, 2015

Internet Connection එකක් නැතුව .NET Framework 3.5 Install කරන හැටි.

අපි අද පාවිච්චි කරන ගොඩක් Software ව්ලට ඕන් දෙයක් තමයි Microsoft .NET Framework කියන්නේ.එක එක සොෆ්ට්වෙයාර් වලට ඕන එක එක Frameworks :). ඒ කියන්නෙ සමහර සොෆ්ට්වෙයාර් වලට ඕන .NET Framework 2.0. සමහර සොෆ්ට්වෙයාර් වලට ඕන .NET Framework 3.5. මේ වගේ අවශ්‍ය Frameworks වෙනස් වෙනවා. ඒත් ගොඩක් Software වලට අවශ්‍ය එකක් තමයි .NET Framework 3.5 . Windows 7 තියනවනම් අපිට .NET Framework 3.5 අමුතුවෙන් ඉන්ස්ටෝල් කරන්න දෙයක් නෑ.මොකද Windows 7 ඉන්ස්ටෝල් කරනකොට මෙකත් ඉබේම ඉන්ස්ටෝල් වෙනවා.

ඒත් ඔයාලා වැඩ කරන්නෙ Windows 8 වල හරි 8.1 වල හරි නම් ඔයාලට .NET Framework 3.5 වෙනමම ඉන්ස්ටෝල් කරන්න වෙනවා.Windows 8 හරි 8.1 වල හරි .NET Framework 3.5 අවශ්‍ය වෙන ප්‍රොග්‍රැම් 1ක් run කරොත් ඔයාලා .NET Framework 3.5 ඉන්ස්ටෝල කරලා නැත්තම් මේ වගෙ Dialog box 1ක් එයි.




අපි Install this feature කියන Option 1 තේරුවොත් ඉන්ටෙර්නෙට් Connect වෙලා .NET Framework 3.5 Download කරල Install කරනවා.

නමුත් මේ ලිපියෙන් අපි බලමු Internet Connection 1 ක් නැතිව කොහොමද .NET Framework 3.5 Install කරන්නෙ කියලා.


  1. ඉස්සෙල්ලම අපිට ඕන Windows 8 ISO File 1ක් හරි Setup disk 1ක් හරි. අපි ලඟ තියෙන්නෙ ISO File 1ක් නම් Power ISO,7-Zip වගේ Software 1ක් පාවිච්චි කරලා ISO File 1ක Extract කරගන්න ඕන.(මේකෙදි ඔයාලට ලේසි විදිහකට Extract කරගන්න.)අපි ලඟ තියෙනනේ Setup Disk 1ක් නම් කරන්න තියෙන්නෙ නිකන්ම Disk 1 CD/DVD Drive 1ට ඇතුල් කරන්න විතරයි.
  2. ඊලඟට Command Prompt 1 Open කරන්න ඕන (As Administrator).
  3. ඊට පස්සෙ පහල තියන Command 1 Command Prompt 1කේ Type කරලා Enter කරන්න (කැමති නම් Paste කරන්නත් පුලුවන් :-) )
          Dism /online /enable-feature /featurename:NetFx3 /All /Source:F:\sources\sxs /LimitAccess 

     මේකෙ "F:" කියන්නෙ Setup Disk 1 තියන CD/DVD Drive එකේ Drive Letter 1.අපි අපේ System 1 ට අනුව ගැලපෙන Drive Letter 1 යොදන්න ඕන.

අපි ISO File 1ක් extract කරා නම් "F:\sources\sxs /LimitAccess " කොටස වෙනුවට ගැලපෙන File Path එක දෙන්න ඕන.

ඒ Command 1 execute කරපු ගමන්ම .NET Framework 3.5 Install වෙන්න පටන් ගන්නවා.ඊට පස්සෙ කරන්න තියෙන්නෙ Install වෙලා ඉවර වෙනකම් බලගෙන ඉන්න විතරයි.



   මේ ක්‍රමයට ගොඩක් ලේසියෙන්, Internet Connection එකක් නැතුව .NET Framework 3.5 install  කරගන්න පුලුවන්.









Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...