Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

INDO GLOBAL COLLEGE OF

ENGINEERING
New Chandigarh, District Mohali Abhipur, Punjab

LAB ON ADVANCED DATA


STRUCTURES
MTCS103-18

Submitted To: Submitted By:


Mr. Bhupinder Singh Mir Auqib Yaqoob
(HOD) M TECH CSE 1st Sem
1807287
EXP 1: WAP to store k keys into an array of size n at the location computed
using a hash function, loc = key % n, where k<=n and k takes values from [1 to
m], m>n. To handle the collisions use the following collision resolution
techniques, a. Linear probing b. Quadratic probing c. Double
hashing/rehashing d. Chaining
**
* Java Program to implement Linear Probing Hash Table
**/

mport java.util.Scanner;

** Class LinearProbingHashTable **/


lass LinearProbingHashTable
{
private int currentSize, maxSize;
private String[] keys;
private String[] vals;

/** Constructor **/


public LinearProbingHashTable(int capacity)
{
currentSize = 0;
maxSize = capacity;
keys = new String[maxSize];
vals = new String[maxSize];
}

/** Function to clear hash table **/


public void makeEmpty()
{
currentSize = 0;
keys = new String[maxSize];
vals = new String[maxSize];
}

/** Function to get size of hash table **/


public int getSize()
{
return currentSize;
}

/** Function to check if hash table is full **/


public boolean isFull()
{
return currentSize == maxSize;
}

/** Function to check if hash table is empty **/


public boolean isEmpty()
{
return getSize() == 0;
}

/** Fucntion to check if hash table contains a key **/


public boolean contains(String key)
{
return get(key) != null;
}

/** Functiont to get hash code of a given key **/


private int hash(String key)
{
return key.hashCode() % maxSize;
}

/** Function to insert key-value pair **/


public void insert(String key, String val)
{
int tmp = hash(key);
int i = tmp;
do
{
if (keys[i] == null)
{
keys[i] = key;
vals[i] = val;
currentSize++;
return;
}
if (keys[i].equals(key))
{
vals[i] = val;
return;
}
i = (i + 1) % maxSize;
} while (i != tmp);
}

/** Function to get value for a given key **/


public String get(String key)
{
int i = hash(key);
while (keys[i] != null)
{
if (keys[i].equals(key))
return vals[i];
i = (i + 1) % maxSize;
}
return null;
}

/** Function to remove key and its value **/


public void remove(String key)
{
if (!contains(key))
return;

/** find position key and delete **/


int i = hash(key);
while (!key.equals(keys[i]))
i = (i + 1) % maxSize;
keys[i] = vals[i] = null;

/** rehash all keys **/


for (i = (i + 1) % maxSize; keys[i] != null; i = (i + 1) % maxSize)
{
String tmp1 = keys[i], tmp2 = vals[i];
keys[i] = vals[i] = null;
currentSize--;
insert(tmp1, tmp2);
}
currentSize--;
}

/** Function to print HashTable **/


public void printHashTable()
{
System.out.println("\nHash Table: ");
for (int i = 0; i < maxSize; i++)
if (keys[i] != null)
System.out.println(keys[i] +" "+ vals[i]);
System.out.println();
}
}

/** Class LinearProbingHashTableTest **/


public class LinearProbingHashTableTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hash Table Test\n\n");
System.out.println("Enter size");
/** maxSizeake object of LinearProbingHashTable **/
LinearProbingHashTable lpht = new LinearProbingHashTable(scan.nextInt() );

char ch;
/** Perform LinearProbingHashTable operations **/
do
{
System.out.println("\nHash Table Operations\n");
System.out.println("1. insert ");
System.out.println("2. remove");
System.out.println("3. get");
System.out.println("4. clear");
System.out.println("5. size");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter key and value");
lpht.insert(scan.next(), scan.next() );
break;
case 2 :
System.out.println("Enter key");
lpht.remove( scan.next() );
break;
case 3 :
System.out.println("Enter key");
System.out.println("Value = "+ lpht.get( scan.next() ));
break;
case 4 :
lpht.makeEmpty();
System.out.println("Hash Table Cleared\n");
break;
case 5 :
System.out.println("Size = "+ lpht.getSize() );
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/** Display hash table **/
lpht.printHashTable();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
EXP 2: WAP for Binary Search Tree to implement following operations: a. Insertion b. Deletion i.
Delete node with only child ii. Delete node with both children c. finding an element

/*
* Java Program to Implement Binary Tree
*/

import java.util.Scanner;

/* Class BTNode */
class BTNode
{
BTNode left, right;
int data;

/* Constructor */
public BTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BTNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BTNode n)
{
right = n;
}
/* Function to get left node */
public BTNode getLeft()
{
return left;
}
/* Function to get right node */
public BTNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}

/* Class BT */
class BT
{
private BTNode root;

/* Constructor */
public BT()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BTNode insert(BTNode node, int data)
{
if (node == null)
node = new BTNode(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
/* Function to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Function to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BTNode r, int val)
{
if (r.getData() == val)
return true;
if (r.getLeft() != null)
if (search(r.getLeft(), val))
return true;
if (r.getRight() != null)
if (search(r.getRight(), val))
return true;
return false;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
private void preorder(BTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(root);
}
private void postorder(BTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}
}

/* Class BinaryTree */
public class BinaryTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of BT */
BT bt = new BT();
/* Perform tree operations */
System.out.println("Binary Tree Test\n");
char ch;
do
{
System.out.println("\nBinary Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. search");
System.out.println("3. count nodes");
System.out.println("4. check empty");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
bt.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ bt.search( scan.nextInt() ));
break;
case 3 :
System.out.println("Nodes = "+ bt.countNodes());
break;
case 4 :
System.out.println("Empty status = "+ bt.isEmpty());
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display tree */
System.out.print("\nPost order : ");
bt.postorder();
System.out.print("\nPre order : ");
bt.preorder();
System.out.print("\nIn order : ");
bt.inorder();

System.out.println("\n\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
EXP 3: WAP for AVL Tree to implement following operations: (For nodes as integers)
/*
* Java Program to Implement AVL Tree
*/

import java.util.Scanner;

/* Class AVLNode */
class AVLNode
{
AVLNode left, right;
int data;
int height;

/* Constructor */
public AVLNode()
{
left = null;
right = null;
data = 0;
height = 0;
}
/* Constructor */
public AVLNode(int n)
{
left = null;
right = null;
data = n;
height = 0;
}
}

/* Class AVLTree */
class AVLTree
{
private AVLNode root;

/* Constructor */
public AVLTree()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Make the tree logically empty */
public void makeEmpty()
{
root = null;
}
/* Function to insert data */
public void insert(int data)
{
root = insert(data, root);
}
/* Function to get height of node */
private int height(AVLNode t )
{
return t == null ? -1 : t.height;
}
/* Function to max of left/right node */
private int max(int lhs, int rhs)
{
return lhs > rhs ? lhs : rhs;
}
/* Function to insert data recursively */
private AVLNode insert(int x, AVLNode t)
{
if (t == null)
t = new AVLNode(x);
else if (x < t.data)
{
t.left = insert( x, t.left );
if( height( t.left ) - height( t.right ) == 2 )
if( x < t.left.data )
t = rotateWithLeftChild( t );
else
t = doubleWithLeftChild( t );
}
else if( x > t.data )
{
t.right = insert( x, t.right );
if( height( t.right ) - height( t.left ) == 2 )
if( x > t.right.data)
t = rotateWithRightChild( t );
else
t = doubleWithRightChild( t );
}
else
; // Duplicate; do nothing
t.height = max( height( t.left ), height( t.right ) ) + 1;
return t;
}
/* Rotate binary tree node with left child */
private AVLNode rotateWithLeftChild(AVLNode k2)
{
AVLNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = max( height( k2.left ), height( k2.right ) ) + 1;
k1.height = max( height( k1.left ), k2.height ) + 1;
return k1;
}

/* Rotate binary tree node with right child */


private AVLNode rotateWithRightChild(AVLNode k1)
{
AVLNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
k1.height = max( height( k1.left ), height( k1.right ) ) + 1;
k2.height = max( height( k2.right ), k1.height ) + 1;
return k2;
}
/**
* Double rotate binary tree node: first left child
* with its right child; then node k3 with new left child */
private AVLNode doubleWithLeftChild(AVLNode k3)
{
k3.left = rotateWithRightChild( k3.left );
return rotateWithLeftChild( k3 );
}
/**
* Double rotate binary tree node: first right child
* with its left child; then node k1 with new right child */
private AVLNode doubleWithRightChild(AVLNode k1)
{
k1.right = rotateWithLeftChild( k1.right );
return rotateWithRightChild( k1 );
}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
private int countNodes(AVLNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.left);
l += countNodes(r.right);
return l;
}
}
/* Functions to search for an element */
public boolean search(int val)
{
return search(root, val);
}
private boolean search(AVLNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.data;
if (val < rval)
r = r.left;
else if (val > rval)
r = r.right;
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(AVLNode r)
{
if (r != null)
{
inorder(r.left);
System.out.print(r.data +" ");
inorder(r.right);
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
private void preorder(AVLNode r)
{
if (r != null)
{
System.out.print(r.data +" ");
preorder(r.left);
preorder(r.right);
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(root);
}
private void postorder(AVLNode r)
{
if (r != null)
{
postorder(r.left);
postorder(r.right);
System.out.print(r.data +" ");
}
}
}

/* Class AVL Tree Test */


public class AVLTreeTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of AVLTree */
AVLTree avlt = new AVLTree();

System.out.println("AVLTree Tree Test\n");


char ch;
/* Perform tree operations */
do
{
System.out.println("\nAVLTree Operations\n");
System.out.println("1. insert ");
System.out.println("2. search");
System.out.println("3. count nodes");
System.out.println("4. check empty");
System.out.println("5. clear tree");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
avlt.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ avlt.search( scan.nextInt() ));
break;
case 3 :
System.out.println("Nodes = "+ avlt.countNodes());
break;
case 4 :
System.out.println("Empty status = "+ avlt.isEmpty());
break;
case 5 :
System.out.println("\nTree Cleared");
avlt.makeEmpty();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display tree */
System.out.print("\nPost order : ");
avlt.postorder();
System.out.print("\nPre order : ");
avlt.preorder();
System.out.print("\nIn order : ");
avlt.inorder();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
EXP 4: WAP to implement Red-Black trees with insertion and deletion
operation for the given input data as Integers/Strings
/*
* Java Program to Implement Red Black Tree
*/

import java.util.Scanner;

/* Class Node */
class RedBlackNode
{
RedBlackNode left, right;
int element;
int color;

/* Constructor */
public RedBlackNode(int theElement)
{
this( theElement, null, null );
}
/* Constructor */
public RedBlackNode(int theElement, RedBlackNode lt, RedBlackNode rt)
{
left = lt;
right = rt;
element = theElement;
color = 1;
}
}

/* Class RBTree */
class RBTree
{
private RedBlackNode current;
private RedBlackNode parent;
private RedBlackNode grand;
private RedBlackNode great;
private RedBlackNode header;
private static RedBlackNode nullNode;
/* static initializer for nullNode */
static
{
nullNode = new RedBlackNode(0);
nullNode.left = nullNode;
nullNode.right = nullNode;
}
/* Black - 1 RED - 0 */
static final int BLACK = 1;
static final int RED = 0;
/* Constructor */
public RBTree(int negInf)
{
header = new RedBlackNode(negInf);
header.left = nullNode;
header.right = nullNode;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return header.right == nullNode;
}
/* Make the tree logically empty */
public void makeEmpty()
{
header.right = nullNode;
}
/* Function to insert item */
public void insert(int item )
{
current = parent = grand = header;
nullNode.element = item;
while (current.element != item)
{
great = grand;
grand = parent;
parent = current;
current = item < current.element ? current.left : current.right;
// Check if two red children and fix if so
if (current.left.color == RED && current.right.color == RED)
handleReorient( item );
}
// Insertion fails if already present
if (current != nullNode)
return;
current = new RedBlackNode(item, nullNode, nullNode);
// Attach to parent
if (item < parent.element)
parent.left = current;
else
parent.right = current;
handleReorient( item );
}
private void handleReorient(int item)
{
// Do the color flip
current.color = RED;
current.left.color = BLACK;
current.right.color = BLACK;

if (parent.color == RED)
{
// Have to rotate
grand.color = RED;
if (item < grand.element != item < parent.element)
parent = rotate( item, grand ); // Start dbl rotate
current = rotate(item, great );
current.color = BLACK;
}
// Make root black
header.right.color = BLACK;
}
private RedBlackNode rotate(int item, RedBlackNode parent)
{
if(item < parent.element)
return parent.left = item < parent.left.element ? rotateWithLeftChild(parent.left) :
rotateWithRightChild(parent.left) ;
else
return parent.right = item < parent.right.element ? rotateWithLeftChild(parent.right) :
rotateWithRightChild(parent.right);
}
/* Rotate binary tree node with left child */
private RedBlackNode rotateWithLeftChild(RedBlackNode k2)
{
RedBlackNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
/* Rotate binary tree node with right child */
private RedBlackNode rotateWithRightChild(RedBlackNode k1)
{
RedBlackNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(header.right);
}
private int countNodes(RedBlackNode r)
{
if (r == nullNode)
return 0;
else
{
int l = 1;
l += countNodes(r.left);
l += countNodes(r.right);
return l;
}
}
/* Functions to search for an element */
public boolean search(int val)
{
return search(header.right, val);
}
private boolean search(RedBlackNode r, int val)
{
boolean found = false;
while ((r != nullNode) && !found)
{
int rval = r.element;
if (val < rval)
r = r.left;
else if (val > rval)
r = r.right;
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(header.right);
}
private void inorder(RedBlackNode r)
{
if (r != nullNode)
{
inorder(r.left);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
inorder(r.right);
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(header.right);
}
private void preorder(RedBlackNode r)
{
if (r != nullNode)
{
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
preorder(r.left);
preorder(r.right);
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(header.right);
}
private void postorder(RedBlackNode r)
{
if (r != nullNode)
{
postorder(r.left);
postorder(r.right);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
}
}
}

/* Class RedBlackTreeTest */
public class RedBlackTreeTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of RedBlack Tree */
RBTree rbt = new RBTree(Integer.MIN_VALUE);
System.out.println("Red Black Tree Test\n");
char ch;
/* Perform tree operations */
do
{
System.out.println("\nRed Black Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. search");
System.out.println("3. count nodes");
System.out.println("4. check empty");
System.out.println("5. clear tree");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
rbt.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ rbt.search( scan.nextInt() ));
break;
case 3 :
System.out.println("Nodes = "+ rbt.countNodes());
break;
case 4 :
System.out.println("Empty status = "+ rbt.isEmpty());
break;
case 5 :
System.out.println("\nTree Cleared");
rbt.makeEmpty();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display tree */
System.out.print("\nPost order : ");
rbt.postorder();
System.out.print("\nPre order : ");
rbt.preorder();
System.out.print("\nIn order : ");
rbt.inorder();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
EXP 5: WAP to implement insertion, deletion, display and search operation in m-way B
tree (i.e. a non-leaf node can have at most m children) for the given data as integers.
//Java implementation to find leaf count of a given Binary tree

/* Class containing left and right child of current


node and key value*/
class Node
{
int data;
Node left, right;

public Node(int item)


{
data = item;
left = right = null;
}
}
public class BinaryTree
{
//Root of the Binary Tree
Node root;
/* Function to get the count of leaf nodes in a binary tree*/
int getLeafCount()
{
return getLeafCount(root);
}
int getLeafCount(Node node)
{
if (node == null)
return 0;
if (node.left == null && node.right == null)
return 1;
else
return getLeafCount(node.left) + getLeafCount(node.right);
}
/* Driver program to test above functions */
public static void main(String args[])
{
/* create a tree */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* get leaf count of the abve tree */
System.out.println("The leaf count of binary tree is : "
+ tree.getLeafCount());
}
}
EXP 6: WAP to perform string matching using Knuth-Morris-Pratt algorithm.

1. /**
2. ** Java Program to implement Knuth Morris Pratt Algorithm
3. **/
4.
5. import java.io.BufferedReader;
6. import java.io.InputStreamReader;
7. import java.io.IOException;
8.
9. /** Class KnuthMorrisPratt **/
10. public class KnuthMorrisPratt
11. {
12. /** Failure array **/
13. private int[] failure;
14. /** Constructor **/
15. public KnuthMorrisPratt(String text, String pat)
16. {
17. /** pre construct failure array for a pattern **/
18. failure = new int[pat.length()];
19. fail(pat);
20. /** find match **/
21. int pos = posMatch(text, pat);
22. if (pos == -1)
23. System.out.println("\nNo match found");
24. else
25. System.out.println("\nMatch found at index "+ pos);
26. }
27. /** Failure function for a pattern **/
28. private void fail(String pat)
29. {
30. int n = pat.length();
31. failure[0] = -1;
32. for (int j = 1; j < n; j++)
33. {
34. int i = failure[j - 1];
35. while ((pat.charAt(j) != pat.charAt(i + 1)) && i >= 0)
36. i = failure[i];
37. if (pat.charAt(j) == pat.charAt(i + 1))
38. failure[j] = i + 1;
39. else
40. failure[j] = -1;
41. }
42. }
43. /** Function to find match for a pattern **/
44. private int posMatch(String text, String pat)
45. {
46. int i = 0, j = 0;
47. int lens = text.length();
48. int lenp = pat.length();
49. while (i < lens && j < lenp)
50. {
51. if (text.charAt(i) == pat.charAt(j))
52. {
53. i++;
54. j++;
55. }
56. else if (j == 0)
57. i++;
58. else
59. j = failure[j - 1] + 1;
60. }
61. return ((j == lenp) ? (i - lenp) : -1);
62. }
63. /** Main Function **/
64. public static void main(String[] args) throws IOException
65. {
66. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
67. System.out.println("Knuth Morris Pratt Test\n");
68. System.out.println("\nEnter Text\n");
69. String text = br.readLine();
70. System.out.println("\nEnter Pattern\n");
71. String pattern = br.readLine();
72. KnuthMorrisPratt kmp = new KnuthMorrisPratt(text, pattern);
73. }
74. }
EXP 7: WAP to perform string matching using Boyer-Moore algorithm.

/**

** Java Program to implement Boyer Moore Algorithm

**/

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

/** Class BoyerMoore **/

public class BoyerMoore

/** function findPattern **/

public void findPattern(String t, String p)

char[] text = t.toCharArray();

char[] pattern = p.toCharArray();

int pos = indexOf(text, pattern);

if (pos == -1)

System.out.println("\nNo Match\n");

else

System.out.println("Pattern found at position : "+ pos);

/** Function to calculate index of pattern substring **/

public int indexOf(char[] text, char[] pattern)


{

if (pattern.length == 0)

return 0;

int charTable[] = makeCharTable(pattern);

int offsetTable[] = makeOffsetTable(pattern);

for (int i = pattern.length - 1, j; i < text.length;)

for (j = pattern.length - 1; pattern[j] == text[i]; --i, --j)

if (j == 0)

return i;

// i += pattern.length - j; // For naive method

i += Math.max(offsetTable[pattern.length - 1 - j], charTable[text[i]]);

return -1;

/** Makes the jump table based on the mismatched character information **/

private int[] makeCharTable(char[] pattern)

final int ALPHABET_SIZE = 256;

int[] table = new int[ALPHABET_SIZE];

for (int i = 0; i < table.length; ++i)

table[i] = pattern.length;

for (int i = 0; i < pattern.length - 1; ++i)

table[pattern[i]] = pattern.length - 1 - i;

return table;
}

/** Makes the jump table based on the scan offset which mismatch occurs. **/

private static int[] makeOffsetTable(char[] pattern)

int[] table = new int[pattern.length];

int lastPrefixPosition = pattern.length;

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

if (isPrefix(pattern, i + 1))

lastPrefixPosition = i + 1;

table[pattern.length - 1 - i] = lastPrefixPosition - i + pattern.length - 1;

for (int i = 0; i < pattern.length - 1; ++i)

int slen = suffixLength(pattern, i);

table[slen] = pattern.length - 1 - i + slen;

return table;

/** function to check if needle[p:end] a prefix of pattern **/

private static boolean isPrefix(char[] pattern, int p)

for (int i = p, j = 0; i < pattern.length; ++i, ++j)

if (pattern[i] != pattern[j])

return false;
return true;

/** function to returns the maximum length of the substring ends at p and is a suffix **/

private static int suffixLength(char[] pattern, int p)

int len = 0;

for (int i = p, j = pattern.length - 1; i >= 0 && pattern[i] == pattern[j]; --i, --j)

len += 1;

return len;

/** Main Function **/

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

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Boyer Moore Algorithm Test\n");

System.out.println("\nEnter Text\n");

String text = br.readLine();

System.out.println("\nEnter Pattern\n");

String pattern = br.readLine();

BoyerMoore bm = new BoyerMoore();

bm.findPattern(text, pattern);

}
EXP 8:WAP to implement 2-D range search over computational geometry problem
//This is a java program to construct a KD tree for two dimensional static data
import java.io.IOException;

class KD2DNode
{
int axis;
double[] x;
int id;
boolean checked;
boolean orientation;

KD2DNode Parent;
KD2DNode Left;
KD2DNode Right;

public KD2DNode(double[] x0, int axis0)


{
x = new double[2];
axis = axis0;
for (int k = 0; k < 2; k++)
x[k] = x0[k];

Left = Right = Parent = null;


checked = false;
id = 0;
}

public KD2DNode FindParent(double[] x0)


{
KD2DNode parent = null;
KD2DNode next = this;
int split;
while (next != null)
{
split = next.axis;
parent = next;
if (x0[split] > next.x[split])
next = next.Right;
else
next = next.Left;
}
return parent;
}

public KD2DNode Insert(double[] p)


{
x = new double[2];
KD2DNode parent = FindParent(p);
if (equal(p, parent.x, 2) == true)
return null;

KD2DNode newNode = new KD2DNode(p,


parent.axis + 1 < 2 ? parent.axis + 1 : 0);
newNode.Parent = parent;

if (p[parent.axis] > parent.x[parent.axis])


{
parent.Right = newNode;
newNode.orientation = true; //
} else
{
parent.Left = newNode;
newNode.orientation = false; //
}

return newNode;
}

boolean equal(double[] x1, double[] x2, int dim)


{
for (int k = 0; k < dim; k++)
{
if (x1[k] != x2[k])
return false;
}

return true;
}

double distance2(double[] x1, double[] x2, int dim)


{
double S = 0;
for (int k = 0; k < dim; k++)
S += (x1[k] - x2[k]) * (x1[k] - x2[k]);
return S;
}
}

class KD2DTree
{
KD2DNode Root;

int TimeStart, TimeFinish;


int CounterFreq;

double d_min;
KD2DNode nearest_neighbour;

int KD_id;

int nList;

KD2DNode CheckedNodes[];
int checked_nodes;
KD2DNode List[];

double x_min[], x_max[];


boolean max_boundary[], min_boundary[];
int n_boundary;

public KD2DTree(int i)
{
Root = null;
KD_id = 1;
nList = 0;
List = new KD2DNode[i];
CheckedNodes = new KD2DNode[i];
max_boundary = new boolean[2];
min_boundary = new boolean[2];
x_min = new double[2];
x_max = new double[2];
}

public boolean add(double[] x)


{
if (nList >= 2000000 - 1)
return false; // can't add more points

if (Root == null)
{
Root = new KD2DNode(x, 0);
Root.id = KD_id++;
List[nList++] = Root;
} else
{
KD2DNode pNode;
if ((pNode = Root.Insert(x)) != null)
{
pNode.id = KD_id++;
List[nList++] = pNode;
}
}

return true;
}

public KD2DNode find_nearest(double[] x)


{
if (Root == null)
return null;

checked_nodes = 0;
KD2DNode parent = Root.FindParent(x);
nearest_neighbour = parent;
d_min = Root.distance2(x, parent.x, 2);
;

if (parent.equal(x, parent.x, 2) == true)


return nearest_neighbour;

search_parent(parent, x);
uncheck();

return nearest_neighbour;
}

public void check_subtree(KD2DNode node, double[] x)


{
if ((node == null) || node.checked)
return;

CheckedNodes[checked_nodes++] = node;
node.checked = true;
set_bounding_cube(node, x);
int dim = node.axis;
double d = node.x[dim] - x[dim];

if (d * d > d_min)
{
if (node.x[dim] > x[dim])
check_subtree(node.Left, x);
else
check_subtree(node.Right, x);
} else
{
check_subtree(node.Left, x);
check_subtree(node.Right, x);
}
}

public void set_bounding_cube(KD2DNode node, double[] x)


{
if (node == null)
return;
int d = 0;
double dx;
for (int k = 0; k < 2; k++)
{
dx = node.x[k] - x[k];
if (dx > 0)
{
dx *= dx;
if (!max_boundary[k])
{
if (dx > x_max[k])
x_max[k] = dx;
if (x_max[k] > d_min)
{
max_boundary[k] = true;
n_boundary++;
}
}
} else
{
dx *= dx;
if (!min_boundary[k])
{
if (dx > x_min[k])
x_min[k] = dx;
if (x_min[k] > d_min)
{
min_boundary[k] = true;
n_boundary++;
}
}
}
d += dx;
if (d > d_min)
return;

if (d < d_min)
{
d_min = d;
nearest_neighbour = node;
}
}

public KD2DNode search_parent(KD2DNode parent, double[] x)


{
for (int k = 0; k < 2; k++)
{
x_min[k] = x_max[k] = 0;
max_boundary[k] = min_boundary[k] = false; //
}
n_boundary = 0;

KD2DNode search_root = parent;


while (parent != null && (n_boundary != 2 * 2))
{
check_subtree(parent, x);
search_root = parent;
parent = parent.Parent;
}

return search_root;
}

public void uncheck()


{
for (int n = 0; n < checked_nodes; n++)
CheckedNodes[n].checked = false;
}

public void inorder()


{
inorder(Root);
}

private void inorder(KD2DNode root)


{
if (root != null)
{
inorder(root.Left);
System.out.print("(" + root.x[0] + ", " + root.x[1] + ") ");
inorder(root.Right);
}
}

public void preorder()


{
preorder(Root);
}

private void preorder(KD2DNode root)


{
if (root != null)
{
System.out.print("(" + root.x[0] + ", " + root.x[1] + ") ");
inorder(root.Left);
inorder(root.Right);
}
}

public void postorder()


{
postorder(Root);
}

private void postorder(KD2DNode root)


{
if (root != null)
{
inorder(root.Left);
inorder(root.Right);
System.out.print("(" + root.x[0] + ", " + root.x[1] + ") ");
}
}
}

public class KDTree_TwoD_Data


{
public static void main(String args[]) throws IOException
{
int numpoints = 5;

KD2DTree kdt = new KD2DTree(numpoints);


double x[] = new double[2];

x[0] = 0.0;
x[1] = 0.0;
kdt.add(x);

x[0] = 3.3;
x[1] = 1.5;
kdt.add(x);

x[0] = 4.7;
x[1] = 11.1;
kdt.add(x);

x[0] = 5.0;
x[1] = 12.3;
kdt.add(x);

x[0] = 5.1;
x[1] = 1.2;
kdt.add(x);

System.out.println("Inorder of 2D Kd tree: ");


kdt.inorder();

System.out.println("\nPreorder of 2D Kd tree: ");


kdt.preorder();

System.out.println("\nPostorder of 2D Kd tree: ");


kdt.postorder();
}
}
EXP 9:WAP on latest efficient algorithms on trees for solving contemporary problems

package practice;
// Java program to create a custom tree from a given set of links.

// The main class that represents tree and has main method
public class Tree {

private TreeNode root;

/* Returns an array of trees from links input. Links are assumed to


be Strings of the form "<s> <e>" where <s> and <e> are starting
and ending points for the link. The returned array is of size 26
and has non-null values at indexes corresponding to roots of trees
in output */
public Tree[] buildFromLinks(String [] links) {

// Create two arrays for nodes and forest


TreeNode[] nodes = new TreeNode[26];
Tree[] forest = new Tree[26];

// Process each link


for (String link : links) {

// Find the two ends of current link


String[] ends = link.split(" ");
int start = (int) (ends[0].charAt(0) - 'a'); // Start node
int end = (int) (ends[1].charAt(0) - 'a'); // End node

// If start of link not seen before, add it two both arrays


if (nodes[start] == null)
{
nodes[start] = new TreeNode((char) (start + 'a'));

// Note that it may be removed later when this


character is
// last character of a link. For example, let we first
see
// a--->b, then c--->a. We first add 'a' to array of
trees
// and when we see link c--->a, we remove it from trees
array.
forest[start] = new Tree(nodes[start]);

// If end of link is not seen before, add it to the nodes


array
if (nodes[end] == null)

nodes[end] = new TreeNode((char) (end + 'a'));

// If end of link is seen before, remove it from forest if


// it exists there.
else forest[end] = null;

// Establish Parent-Child Relationship between Start and End


nodes[start].addChild(nodes[end], end);
}
return forest;
}

// Constructor
public Tree(TreeNode root) { this.root = root; }

public static void printForest(String[] links)


{
Tree t = new Tree(new TreeNode('\0'));
for (Tree t1 : t.buildFromLinks(links)) {
if (t1 != null)
{
t1.root.printTreeIdented("");
System.out.println("");
}
}
}

// Driver method to test


public static void main(String[] args) {
String [] links1 = {"a b", "b c", "b d", "a e"};
System.out.println("------------ Forest 1 ----------------");
printForest(links1);

String [] links2 = {"a b", "a g", "b c", "c d", "d e", "c f",
"z y", "y x", "x w"};
System.out.println("------------ Forest 2 ----------------");
printForest(links2);
}
}

// Class to represent a tree node


class TreeNode {
TreeNode []children;
char c;

// Adds a child 'n' to this node


public void addChild(TreeNode n, int index) { this.children[index] = n;}

// Constructor
public TreeNode(char c) { this.c = c; this.children = new TreeNode[26];}

// Recursive method to print indented tree rooted with this node.


public void printTreeIdented(String indent) {
System.out.println(indent + "-->" + c);
for (TreeNode child : children) {
if (child != null)
child.printTreeIdented(indent + " |");
}
}
}

You might also like