Aug 28, 2016

Bash Shell Script Sample Code - Part 1

1. Read user input and display message Welcome

#!/bin/bash
echo 'read_input=?' ; 
read read_input
echo "Welcome on $read_input" 
Sample output:
read_input=?
Devinline
Welcome on Devinline

 2. Print Even natural numbers up to given N.
#!/bin/bash
echo 'Enter input value N=?' ; 
read N
x=0 #no space in variable declaration
zero=0
t=9
while [ $x -le $N ]
do
 let p=$x%2; 
 if [ $p -eq 0 ]
 then
  echo "$x"
 fi
 x=$((x+1))
done
Sample Output:-
[cloudera@quickstart Desktop]$ sh even.sh
Enter input value N=?
15
0
2
4
6
8
10
12
14

3. Print 1 to N  (N is read as user input)
#!/bin/bash
x=1
echo 'Enter input value N=?' ; 
read N
while [ $x -le $N ]
do 
    echo $x
    x=$((x+1)) #Arithmatic compound expression
done
Sample output:-
Enter input value N=?
8
1
2
3
4
5
6
7
8

4. Arithmetic operation - read two number from user and perform addition, subtraction, multiplication and division

#!/bin/bash
echo 'Enter input value1 x=?' ;
read x
echo 'Enter input value2 y=?' ;
read y
echo "Sum is $((x+y))"
echo "Subtraction is $((x-y))"
echo "Multiplication is $((x*y))"
echo "Division is $((x/y))"
Sample Output:-
Enter input value1 x=?
12
Enter input value2 y=?
4
Sum is 16
Subtraction is 8
Multiplication is 48
Division is 3

5. Compare two number entered as user input (If-else block)

#!/bin/bash
echo 'Enter input value1 x=?' ;
read x
echo 'Enter input value2 y=?' ;
read y
if [ $x -gt $y ]
then
 echo "X is greater than Y" 
elif [ $x -lt $y ] 
then 
    echo "X is less than Y"  
else 
    echo "X is equal to Y"
fi 
Sample output:-
Enter input value1 x=?
12
Enter input value2 y=?
34
X is less than Y

6. Using Switch case - Print YES if Y/y is user input and NO for N/n 6666666666666666

#!/bin/bash
echo 'Enter input char=?' ;

read char
case "$char" in
 Y) echo "YES" 
  ;;
 y) echo "YES" 
  ;;
        n) echo "NO" 
  ;;
 N)   echo "NO" ;;
esac
Sample output:-
Enter input char=?
y
YES

7. Check triangle is SCALENE,ISOSCELES or EQUILATERAL . Get sides of triangle as user input. 

#!/bin/bash
echo 'Enter triangle side1 length x=?' ;
read x
echo 'Enter triangle side1 length y=?' ;
read y
echo 'Enter triangle side1 length z=?' ;
read z
if [ $x -eq $y ] && [ $y -eq $z ]
then
    echo "EQUILATERAL triangle"
elif [ $x -eq $y ] ||  [ $y -eq $z  ] || [ $x -eq $z ]
then     
    echo "ISOSCELES triangle"
else
    echo "SCALENE triangle"
fi 
Sample output:-
Enter triangle side1 length x=?
6
Enter triangle side1 length y=?
5
Enter triangle side1 length z=?
5
ISOSCELES triangle

8. Sum of N natural numbers. Take user input value of N.


#!/bin/bash

echo -n "Enter number N=?"
read N

s=0 # here sum

for((i=1; i <=N ; i++))
do
 let s=$s+$i 
done

echo "sum= "$s
Sample output:-
[cloudera@quickstart Desktop]$ sh sum.sh
Enter number N=?5
sum= 15

Aug 27, 2016

Minimum number of character deletions required to make two strings anagrams

Problem statement: Given two strings s1 and s2 such that, they may or may not be of the same length. Determine the minimum number of character deletions required to make s1 and s2 anagrams. Any characters can be deleted from either of the strings.
s1= qcvdb
s2= asbc
output : 5

Complete Sample program :-

import java.util.*;

public class MakeAnagram {
public static int numberNeeded(String first, String second) {
 char[] ch1 = first.toCharArray();
 char[] ch2 = second.toCharArray();
 int count = 0;
 Map<Character, Integer> map = new HashMap<Character, Integer>();
 for (int j = 0; j < ch2.length; j++) {
  char t = ch2[j];
  if (map.get(t) != null) {
   map.put(t, map.get(t) + 1);
  } else {
   map.put(t, 1);
  }
 }

 for (int j = 0; j < ch1.length; j++) {
  char t = ch1[j];
  if (map.get(t) != null) {
   if (map.get(t) != 0)
    map.put(t, map.get(t) - 1);
   else
    count++;
  } else {
   count++;
  }
 }
 int temp = 0;
 for (Character c : map.keySet()) {
  temp += map.get(c);
 }
 System.out.println(temp + " " + count);
 return temp + count;
}

public static void main(String[] args) {
 Scanner in = new Scanner(System.in);
 String input1 = in.next();
 String input2 = in.next();
 System.out.println("No of characters deleted is "+ numberNeeded(first, second));
}
}

Sample output
:-
imkhnpqnhlvaxlmrsskbyyrhwfvgteubrelgubvdmrdmesfxkpykprunzpustowmvhupkqsyjxmnptkcilmzcinbzjwvxshubeln

wfnfdassvfugqjfuruwrdumdmvxpbjcxorettxmpcivurcolxmeagsdundjronoehtyaskpwumqmpgzmtdmbvsykxhblxspgnpgfzydukvizbhlwmaajuytrhxeepvmcltjmroibjsdkbqjnqjwmhsfopjvehhiuctgthrxqjaclqnyjwxxfpdueorkvaspdnywupvmy

No of characters deleted is 102
------------------------------------------------------

Aug 20, 2016

Simulate Unix GREP command in Python

Grep command :- Grep searches the named input FILE's (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN.
By default, grep prints the matching lines.takes 2 parameters "source" and "pattern" that need to be searched.

Sample program simulating grep command:-  

Create a file(fgrepwc.py) with following sample code. Here three command line argument is passed "" i.e : python fgrepwc.py "world" input.txt.

import sys
import string

def findpatterninfile(pattern, filename):
    count = 0
    try:
        filehandle = open(filename,'r')
    except:
        print filename, ":", sys.exec_info()[1]
    allLines = filehandle.readlines()
    filehandle.close()

    for line in allLines :
        if string.find(line,pattern) > -1:
            count = count+1
            sys.stdout.write(line)
    print "\nTotal pattern match count is : " + str(count)
        
def errorreport():
    print "Invalid input/usage"
    sys.exit(1)
    
def validateArgs():
    #agrc = len(sys.argv)
    if len(sys.argv) != 3:
        errorreport()
    else:
        findpatterninfile(sys.argv[1],sys.argv[2])
#Executed directly as application
if __name__ == '__main__':
    validateArgs()

Content of input.txt:- 

Hello world
Read first line.
Python world
world is game

Sample output:- Create input.txt with above lines and execute following command -

> python fgrepwc.py "world" input.txt
Hello world
Python world
world is game
Total line count is : 3

Aug 14, 2016

Textual description of firstImageUrl

Display nodes of binary tree in a vertical line viewed from top and compute sum of vertical line nodes

Problem:- Display nodes of binary tree in a vertical line viewed from top.
Output:-  
Nodes at vertical line
56
11
23 78
12 43 12
18 98
99

Sum at vertical line 
Sum at 0 is/are 67
Sum at 1 is/are 116
Sum at 2 is/are 99
Sum at -3 is/are 56
Sum at -2 is/are 11
Sum at -1 is/are 101

Sample code - Order of O(n2 )

// To find min and max horizontal distance.
public static void findMinMaxHorizontal(Node root, Values val, int hd) {
 if (root == null)
  return;
 if (hd < val.min) {
  val.min = hd;
 } else if (hd > val.max) {
  val.max = hd;
 }
 findMinMaxHorizontal(root.getLeftChild(), val, hd - 1);
 findMinMaxHorizontal(root.getRightChild(), val, hd + 1);
}

// order of o(N2) - worst case complexity
public static void printVerticalOrderOfON2(Node root) {
 Values val = new Values();
 findMinMaxHorizontal(root, val, 0);
 // System.out.println(val.min + " " + val.max);

 for (int i = val.min; i <= val.max; i++) {
  System.out.println("Nodes in horizontal distance  " + i
    + " is/are ");
  printVerticalLineNodes(root, i, 0);

  System.out.println();
 }

}

public static void printVerticalLineNodes(Node root, int line_no, int hd) {

 if (root == null)
  return;
 if (hd == line_no) {
  System.out.print(root.getData() + " ");
 }
 printVerticalLineNodes(root.getLeftChild(), line_no, hd - 1);
 printVerticalLineNodes(root.getRightChild(), line_no, hd + 1);
}
class Values {
 int min;
 int max;
}

Sample code using a HashMap  - Order of O(n ), space complexity also O(n) 

public static void printVerticalOrderHashMapbased(Node root,
  Map<Integer, List<Integer>> hmap, int hd) {
 if (root == null)
  return;
 if (hmap.get(hd) == null) {
  List<Integer> list = new LinkedList<Integer>();
  list.add(root.getData());
  hmap.put(hd, list);
 } else {
  List<Integer> list2 = hmap.get(hd);
  list2.add(root.getData());
  hmap.put(hd, list2);
 }

 printVerticalOrderHashMapbased(root.getLeftChild(), hmap, hd - 1);
 printVerticalOrderHashMapbased(root.getRightChild(), hmap, hd + 1);
}

Complete sample program

package com.devinline.trees;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class BinaryTreeVerticalSum {

// To find min and max horizontal distance.
public static void findMinMaxHorizontal(Node root, Values val, int hd) {
 if (root == null)
  return;
 if (hd < val.min) {
  val.min = hd;
 } else if (hd > val.max) {
  val.max = hd;
 }
 findMinMaxHorizontal(root.getLeftChild(), val, hd - 1);
 findMinMaxHorizontal(root.getRightChild(), val, hd + 1);
}

// order of o(N2) - worst case complexity
public static void printVerticalOrderOfON2(Node root) {
 Values val = new Values();
 findMinMaxHorizontal(root, val, 0);
 // System.out.println(val.min + " " + val.max);

 for (int i = val.min; i <= val.max; i++) {
  System.out.println("Nodes in horizontal distance  " + i
    + " is/are ");
  printVerticalLineNodes(root, i, 0);

  System.out.println();
 }

}

public static void printVerticalLineNodes(Node root, int line_no, int hd) {

 if (root == null)
  return;
 if (hd == line_no) {
  System.out.print(root.getData() + " ");
 }
 printVerticalLineNodes(root.getLeftChild(), line_no, hd - 1);
 printVerticalLineNodes(root.getRightChild(), line_no, hd + 1);
}

public static void printVerticalLineNodesSum(Node root, int hd,
  Map<Integer, Integer> hmap) {
 if (root == null)
  return;

 int prevSum = hmap.get(hd) == null ? 0 : hmap.get(hd);
 hmap.put(hd, prevSum + root.getData());

 printVerticalLineNodesSum(root.getLeftChild(), hd - 1, hmap);
 printVerticalLineNodesSum(root.getRightChild(), hd + 1, hmap);
}

public static void printVerticalOrderHashMapbased(Node root,
  Map<Integer, List<Integer>> hmap, int hd) {
 if (root == null)
  return;
 if (hmap.get(hd) == null) {
  List<Integer> list = new LinkedList<Integer>();
  list.add(root.getData());
  hmap.put(hd, list);
 } else {
  List<Integer> list2 = hmap.get(hd);
  list2.add(root.getData());
  hmap.put(hd, list2);
 }

 printVerticalOrderHashMapbased(root.getLeftChild(), hmap, hd - 1);
 printVerticalOrderHashMapbased(root.getRightChild(), hmap, hd + 1);
}

public static void main(String[] args) {
 BinaryTree bt = new BinaryTree();
 Node root = bt.createTree();
 System.out
 .println("\n====Print vertical elemets of order O(n2)===");
 printVerticalOrderOfON2(root);
 Map<Integer, List<Integer>> hmap2 = new HashMap<>();
 System.out
   .println("\n====Print vertical elemets using hashmap of order O(n)===");
 printVerticalOrderHashMapbased(root, hmap2, 0);
 System.out.println(hmap2.entrySet());
 for (int i : hmap2.keySet()) {
  System.out.println("Nodes with horizontal distance " + i
    + " is/are " + hmap2.get(i));
 }
 Map<Integer, Integer> hmap = new HashMap<>();
 printVerticalLineNodesSum(root, 0, hmap);
 System.out.println("\n===Print sum of vertical elements using hashmap====");
 for (int i : hmap.keySet()) {
  System.out.println("Sum of nodes at horizontal distance " + i
    + " is/are " + hmap.get(i));
 }
}
}

class Values {
int min;
int max;
}
class BinaryTree {
 Node root;

 public BinaryTree() {
  root = null;
 }
 public Node createTree() {
  if (root == null) {
   root = new Node(12);
  }
  root.setLeftChild(new Node(23));
  root.setRightChild(new Node(18));
  root.getLeftChild().setLeftChild(new Node(11));
  root.getLeftChild().setRightChild(new Node(43));
  root.getRightChild().setLeftChild(new Node(12));
  root.getLeftChild().getLeftChild().setLeftChild(new Node(56));
  root.getLeftChild().getLeftChild().setRightChild(new Node(78));
  root.getRightChild().getLeftChild().setRightChild(new Node(98));
  root.getRightChild().setRightChild(new Node(99));
  return root;
 } 
}

class Node {

 private int data;
 private Node leftChild;
 private Node rightChild;

 public Node(int data) {
  this.data = data;
  leftChild = null;
  rightChild = null;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getLeftChild() {
  return leftChild;
 }

 public void setLeftChild(Node leftChild) {
  this.leftChild = leftChild;
 }

 public Node getRightChild() {
  return rightChild;
 }

 public void setRightChild(Node rightChild) {
  this.rightChild = rightChild;
 }

}

Sample output:-


====Print vertical elemets of order O(n2)===
Nodes in horizontal distance  -3 is/are
56
Nodes in horizontal distance  -2 is/are
11
Nodes in horizontal distance  -1 is/are
23 78
Nodes in horizontal distance  0 is/are
12 43 12
Nodes in horizontal distance  1 is/are
18 98
Nodes in horizontal distance  2 is/are
99

====Print vertical elemets using hashmap of order O(n)===
[0=[12, 43, 12], 1=[18, 98], 2=[99], -3=[56], -2=[11], -1=[23, 78]]
Nodes with horizontal distance 0 is/are [12, 43, 12]
Nodes with horizontal distance 1 is/are [18, 98]
Nodes with horizontal distance 2 is/are [99]
Nodes with horizontal distance -3 is/are [56]
Nodes with horizontal distance -2 is/are [11]
Nodes with horizontal distance -1 is/are [23, 78]

===Print sum of vertical elements using hashmap====
Sum of nodes at horizontal distance 0 is/are 67
Sum of nodes at horizontal distance 1 is/are 116
Sum of nodes at horizontal distance 2 is/are 99
Sum of nodes at horizontal distance -3 is/are 56
Sum of nodes at horizontal distance -2 is/are 11
Sum of nodes at horizontal distance -1 is/are 101

Aug 7, 2016

Textual description of firstImageUrl

Traverse all possible path from root to leaves and Display all nodes

Problem:- Display all nodes from root to leaves, consider all possible paths.
Output for above Binary tree:- 12-23-11-56, 12-23-11-78, etc

public static void pathFromtRootToleafs(Node root, Vector<Integer> vector,
   int index) {
  if (root == null)
   return;
  vector.insertElementAt(root.getData(), index);
  index++;
  pathFromtRootToleafs(root.getLeftChild(), vector, index);
  pathFromtRootToleafs(root.getRightChild(), vector, index);
  if (root.getLeftChild() == null && root.getRightChild() == null) {
   
   displayNodes(vector, index);System.out.println("");
  }
 }
Here we are doing pre-order traversal and storing nodes values in a vector till we reach leaf (left and right node are null). Once we reach at leaf node, we call display method with index value to display all nodes.

Complete Sample program:- 

package com.devinline.trees;
import java.util.Vector;

public class AllPathsFromRootToLeafs {

 /**
  * To display all nodes from root to leaf - consider all possible paths
  */
 public static void main(String[] args) {
  Vector<Integer> vector = new Vector<>();
  BinaryTree bt = new BinaryTree();
  Node root = bt.createTree();
  pathFromtRootToleafs(root, vector, 0);
 }

 public static void pathFromtRootToleafs(Node root, Vector<Integer> vector,
   int index) {
  if (root == null)
   return;
  vector.insertElementAt(root.getData(), index);
  index++;
  pathFromtRootToleafs(root.getLeftChild(), vector, index);
  pathFromtRootToleafs(root.getRightChild(), vector, index);
  if (root.getLeftChild() == null && root.getRightChild() == null) {
   
   displayNodes(vector, index);System.out.println("");
  }
 }

 private static void displayNodes(Vector<Integer> vector, int index) {
  for (int i = 0; i < index; i++) {
   System.out.print(vector.get(i) + " ");
  }
 }
}
class BinaryTree {
 Node root;

 public BinaryTree() {
  root = null;
 }
 public Node createTree() {
  if (root == null) {
   root = new Node(12);
  }
  root.setLeftChild(new Node(23));
  root.setRightChild(new Node(18));
  root.getLeftChild().setLeftChild(new Node(11));
  root.getLeftChild().setRightChild(new Node(43));
  root.getRightChild().setLeftChild(new Node(12));
  root.getLeftChild().getLeftChild().setLeftChild(new Node(56));
  root.getLeftChild().getLeftChild().setRightChild(new Node(78));
  root.getRightChild().getLeftChild().setRightChild(new Node(98));
  root.getRightChild().setRightChild(new Node(99));
  return root;
 } 
}

class Node {

 private int data;
 private Node leftChild;
 private Node rightChild;

 public Node(int data) {
  this.data = data;
  leftChild = null;
  rightChild = null;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getLeftChild() {
  return leftChild;
 }

 public void setLeftChild(Node leftChild) {
  this.leftChild = leftChild;
 }

 public Node getRightChild() {
  return rightChild;
 }

 public void setRightChild(Node rightChild) {
  this.rightChild = rightChild;
 }

}

Sample output:
-
12 23 11 56
12 23 11 78
12 23 43
12 18 12 98
12 18 99