Monday, 24 February 2014

Mounting Solaris NFS Share on Linux(Ubuntu)

Basics

  1. When we say we are sharing/mounting partition of one machine on another machine there are some prerequisites that must be first understood and taken care of. First of all both machines must be connected via some network or in other terms both machine must be accessible to each other. How do we check that? -> Simply open command prompt and execute

    ping IPAddress of other machine (Eg. ping 192.168.1.202)

    If the ping is successfull in both ways we are good to proceed.
  2. To fully understand point mentioned above it is important to know that mounting a partition to another machine essentially involves a server-client architecture. The machine whose partition is to be share acts as a server where as machine on which the partition is to be mounted acts as a client.
  3. When we say we have server-client architecture what immediately comes into mind is what rules govern the communication between server and client. More precisely it is called protocol. For eg. files can be shared over FTP(File transfer protocol). For mounting partitions over network we have different set of protocols. Most commonly used are Network File System (NFS) for Linux and Common Internet File System (CIFS) for Windows.
  4. As long as we are on mounting topic it would be beneficial to revise mount and umount System calls as they will be used later.

Before we proceed to see how Solaris partition/share is mounted on a Linux machine you may want to go though how Linux share is mounted on another Linux machine. Following link also provides the basics like installing portmap, understanding exports, mount, umount etc.

How To Set Up an NFS Mount on Ubuntu 12.04 


Mounting Solaris NFS Share on Linux

  1. Create directory on your Solaris machine which you wish to share. Next provide permissions to that directory. You can either use chmod command or you can change permissions from file properties.

  2. By default Solaris or rather mostly all unix based systems have Bourne shell(sh). If you are more comfortable with Bourne Again Shell(bash) like me you can easily switch to it. Steps provided in screen shot below -

  3. Next step is to check if NFS server is up and running. For that you can execute following command in the console -

    svcs | grep nfs

    If you get the output as shown in the screen shot below you are good to proceed. If not then you have to start the nfs server. You can do that with following command -

    svcadm -v enable network/nfs/server
    Similar command goes for disabling the server

    svcadm -v disable network/nfs/server

    Info :
    svcs :- report service status
    For more info execute man svcs on console
    svcadm :- System administation command. Manipulate service instance.
    For more info execute man svcadm on console
  4. Next you need to make an entry of the directory you are going to share in the file /etc/dfs/dfstab. Add following lines to the file and save.(Note : You need su privileges to edit the file).

    #share [-F nfs] [-o specific-options] [-d description] pathname
    share  -F nfs -o rw -d "TestDescription" /Desktop/aniket/mount


  5. Save the changes above and restart the server.Infact for any further changes in this file to take effect you will have to bring down the server amd restart.

    svcadm -v disable network/nfs/server
    svcadm -v enable network/nfs/server
    After restarting the server you can check that that the entry is successfull by executing command - share.
    If you are able to see the entry, execute the command - shareall.
    This will inform your server that the directory represented by the entry made can be shared over the network.
  6. That is all for server(Solaris) side. Now lets move on to Client(Linux/Ubuntu) side. Here you simply need to execute mount system call.

    sudo mount -vt  nfs 192.168.1.202:/Desktop/aniket/mount /home/aniket/SolarisShared/mount/

    or if you wish to remount you can do

    sudo mount -o remount -vt  nfs 192.168.1.202:/Desktop/aniket/mount /home/aniket/SolarisShared/mount/

    By syntax you must have guessed the format is

    mount -vt nfs serverIP:/serverDirPath localDirPath

  7. Finally you can see if the directory is really mounted/mapped. You can see it physically or use the command - mount




Thats all! Let me know if there are any further doubts.

Saturday, 22 February 2014

Lowest Common Ancestor in a Binary Search Tree.

Question : 

Given values of two nodes in a Binary Search Tree, write a c program to find the Lowest Common Ancestor (LCA). You may assume that both the values exist in the tree. (GeeksForGeeks)

LCA(Lowest Common Ancestor) :


Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). 

The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. (Source Wiki

Example :





For example, consider the BST in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8.


Solution :

We can solve this problem using BST properties. We can recursively traverse the BST from root. The main idea of the solution is, while traversing from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 or same as one of the n1 or n2, is LCA of n1 and n2 (assuming that n1 < n2). So just recursively traverse the BST in, if node's value is greater than both n1 and n2 then our LCA lies in left side of the node, if it's is smaller than both n1 and n2, then LCA lies on right side. Otherwise root is LCA (assuming that both n1 and n2 are present in BST)

Code : 

package Tree;

/**
 * Created by Aniket on 2/22/14.
 */
public class LCAFinder {

    public static TreeNode findLCA(TreeNode root, int n1,int n2){

        if(root == null){
            return null;
        }

        int data = root.getData();
        if(data > n1 && data > n2){
            return findLCA(root.getLeftNode(),n1, n2);
        }

        if(data < n1 && data < n2){
            return findLCA(root.getRightNode(), n1, n2);
        }
        return root;
    }

    public static void main(String args[]){

        TreeNode root = new TreeNode(20);

        TreeNode l = new TreeNode(8);
        TreeNode r = new TreeNode(22);

        TreeNode ll = new TreeNode(4);
        TreeNode lr = new TreeNode(12);

        TreeNode lrl = new TreeNode(10);
        TreeNode lrr = new TreeNode(14);

        root.setLeftNode(l);
        root.setRightNode(r);

        l.setLeftNode(ll);
        l.setRightNode(lr);

        lr.setLeftNode(lrl);
        lr.setRightNode(lrr);

        System.out.println("LCA : " + findLCA(root,10,14).getData());
    }
}

Output : 

LCA of Node with data 10 and 14 : 12
(You can similarly execute the code for 8 and 14( Answer is 8))

Important Links : 

  1. Lowest common ancestor
  2. How to find the lowest common ancestor of two nodes in any binary tree?
  3.  Lowest Common Ancestor in a Binary Tree. (OSFG)



Friday, 21 February 2014

Sort a stack using recursion in Java

Question : 

Sorting a Stack using push,pop,isEmpty and peek.

Code :

 package SortingTechniques;

import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 19/2/14
 * Time: 11:02 AM
 */
public class StackSort {

    public void sortStack(Stack<Integer> stack){

        int no = stack.pop();
        if(stack.size() != 1){
            sortStack(stack);
        }
        insert(stack,no);
    }

    private void insert(Stack<Integer> stack, int no){

        if(stack.size() == 0){
            stack.push(no);
        }
        else{
            int newPeakedNo = stack.peek();
            if(no >= newPeakedNo){
                stack.push(no);
            }
            else{
                int newPoppedNo = stack.pop();
                insert(stack, no);
                stack.push(newPoppedNo);
            }
        }
    }

    public static void main(String args[]){

        Stack<Integer> stack = new Stack<>();
        stack.push(5);
        stack.push(4);
        stack.push(3);
        stack.push(2);
        stack.push(1);
        System.out.println("Stack Before Sort : " + Arrays.toString(stack.toArray()));
        new StackSort().sortStack(stack);
        System.out.println("Stack After Sort : " + Arrays.toString(stack.toArray()));

    }

}



Output :

Stack Before Sort : [5, 4, 3, 2, 1]
Stack After Sort : [1, 2, 3, 4, 5]


Note :

A similar question was solver in previous post about how to reverse a Stack in Java. It has similar logic. 

Counting Sort in java

Background

 Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.

Code :

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 19/2/14
 * Time: 8:03 PM
 */
public class CountingSort {


    public int[] sort(int[] array) {

        int maxValue = getMaxValue(array);
        return countingSort(array,maxValue);

    }

    public int[] countingSort(int[] input, int maxValue){

        int[] countArray = new int[maxValue+1];
        for(int no : input){
            countArray[no] = countArray[no] + 1;
        }

        for(int i=1;i<countArray.length;i++){
            countArray[i] = countArray[i] + countArray[i-1];
        }

        int[] output = new int[input.length];

        for(int i=output.length-1;i>=0;i--){

            output[countArray[input[i]]-1] = input[i];
            countArray[input[i]] = countArray[input[i]] -1;

        }

        return output;

    }


    private int getMaxValue(int[] array){

        int maxValue = Integer.MIN_VALUE;
        for(int no : array){
            if(no > maxValue){
                maxValue = no;
            }
        }
        return maxValue;
    }


    public static void main(String args[]){

        int[] array = new int[]{2,7,5,9,4,7,1,0};
        System.out.println("Array Before Sort : " + Arrays.toString(array));
        System.out.println("Array after Sort : " + Arrays.toString(new CountingSort().sort(array)));

    }

}

Output :

Array Before Sort : [2, 7, 5, 9, 4, 7, 1, 0]
Array after Sort : [0, 1, 2, 4, 5, 7, 7, 9]


 NOTE : The modified count array indicates the position of each object in the output sequence.


Time Complexity

Time Complexity: O(n+k) where n is the number of elements in input array and k is the range of input.
Auxiliary Space:
O(n+k)

Related Links

Quick Sort in Java

Background

 Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

Steps :

  1. Pick an element, called a pivot, from the array.
  2. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

Code :

import java.io.IOException;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 19/2/14
 * Time: 8:32 PM
 */
public class QuickSort {

    public void quickSort(int[] array, int start, int end){
        int i = start;
        int j = end;

        int pivot = array[(start + end)/2];

        while (i <= j) {

            while (array[i] < pivot) {
                i++;
            }

            while (array[j] > pivot) {
                j--;
            }

            if (i <= j) {
                swap(array, i, j);
                i++;
                j--;
            }
        }

        if (start < j)
            quickSort(array, start, j);
        if (i < end)
            quickSort(array, i, end);
    }

    public static void swap(int[] array, int index1, int index2){

        if(index1 == index2)
            return;

        int temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;

    }

    public static void main(String args[]) throws IOException {

        int[] array = new int[]{2,7,5,9,4,7,1,0};
        System.out.println("Array Before Sort : " + Arrays.toString(array));
        new QuickSort().quickSort(array,0,array.length-1);
        System.out.println("Array after Sort : " + Arrays.toString(array));

    }
}


Output :

Array Before Sort : [2, 7, 5, 9, 4, 7, 1, 0]
Array after Sort : [0, 1, 2, 4, 5, 7, 7, 9]


 Complexity

Quick sort like merge sort has an average complexity of O(Nlog N)


Worst-case analysis

The most unbalanced partition occurs when one of the sublists returned by the partitioning routine is of size n − 1. This may occur if the pivot happens to be the smallest or largest element in the list, or in some implementations when all the elements are equal.

If this happens repeatedly in every partition, then each recursive call processes a list of size one less than the previous list. Consequently, we can make n − 1 nested calls before we reach a list of size 1. This means that the call tree is a linear chain of n − 1 nested calls. The ith call does O(n − i) work to do the partition, and , so in that case, Quicksort takes O(n²) time.

Best-case analysis

In the most balanced case, each time we perform a partition we divide the list into two nearly equal pieces. This means each recursive call processes a list of half the size. Consequently, we can make only log2 n nested calls before we reach a list of size 1. This means that the depth of the call tree is log2 n. But no two calls at the same level of the call tree process the same part of the original list; thus, each level of calls needs only O(n) time all together (each call has some constant overhead, but since there are only O(n) calls at each level, this is subsumed in the O(n) factor). The result is that the algorithm uses only O(n log n) time.

Average-case analysis

To sort an array of n distinct elements, quicksort takes O(n log n) time in expectation, averaged over all n! permutations of n elements with equal probability. We list here three common proofs to this claim providing different insights into quicksort's workings.

Other Info

 As of Perl 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In Java, the Arrays.sort() methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted. Python uses Timsort, another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in Java SE & on the Android platform, and in GNU Octave.

Related Links

t> UA-39527780-1 back to top