DAA Lab Manual (New Format)
DAA Lab Manual (New Format)
DEPARTMENT
Of
COMPUTER SCIENCE & ENGINEERING
LABORATORY MANUAL
IV Semester
Course objectives: This course will enable students to achieve the following:
Design and implement various algorithms in JAVA ·
Employ various design strategies for problem solving.
Measure and compare the performance of different algorithms.
Course outcomes: At the end of the course, students should be able to:
Lab Experiments:
Design, develop, and implement the specified algorithms for the following problems using Java
language under LINUX /Windows environment .Net beans /Eclipse IDE tool can be used for
development and demonstration.
1 A. Create a Java class called Student with the following details as variables within it. (i) USN (ii)
Name (iii) Branch (iv) Phone Write a Java program to create n Student objects and print the USN, Name,
Branch, and Phone of these objects with suitable headings.
B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working.
2 A. Design a called Staff with details as Staff Id, Name, Phone, Salary. Extend this class by writing
three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write
a Java program to read and display at least 3 staff objects of all three categories.
B. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format
should be dd/mm/yyyy. Write methods to read customer data as and display as using String Tokenizer
class considering the delimiter character as “/”.
3 A. Write a Java program to read two integers a andb. Compute a/b and print, when b is not zero. Raise
an exception when b is equal to zero.
B. Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number and
prints; third thread will print the value of cube of the number.
4 Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run
the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken
versus non graph sheet. The elements can be read from a file or can be generated using the random
number generator. Demonstrate using Java how the divideand-conquer method works along with its time
complexity analysis: worst case, average case and best case.
5 Sort a given set of n integer elements using Merge Sort method and compute its time complexity. Run
the program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the time taken
versus non graph sheet. The elements can be read from a file or can be generated using the random
number generator. Demonstrate using Java how the divide and-conquer method works along with its time
complexity analysis: worst case, average case and best case.
6 Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy
method.
7 From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's
algorithm. Write the program in Java.
9 Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm.
11 Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive integers
whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are
two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a
solution.
12 Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n
vertices using backtracking principle.
Good Average
a. Write up Write the program neatly Moderate understanding of
(3 marks) demonstrating good knowledge of algorithms(2)
concepts and algorithms in java (3)
b. Execution Program handles all possible Average conditions defined
(3 marks) conditions (3) (2)
c. Result All results are correctly Acceptable documentation
(2 marks) demonstrated(2) shown(1)
Good Average
Conceptual Explain the complete program with explanation provided
understanding the related concepts (2) adequately (1)
(2 marks)
Execution plan
WEEK # NAME OF THE EXPERIMENT EXPERIMENT REMARKS
#
1 Create n Student objects and 1 Completed
print the USN, Name, Branch,
and
Phone of these objects &
implement the Stack using
arrays
5 Lab Internal-I
6 Merge sort 5 Completed
8 Implement 7 Completed
Dijikstra's algorithm
13 Lab Internal-II
4 4 Quick sort 10
5 5 Merge sort 10
6 6 Knapsack problem 10
a)Greedy Approach
b)Dynamic programming Approach
7 7 Implement 10
Dijikstra's algorithm
Avg:
Staff signature:
import java.util.Scanner;
class Student {
private String usn, name, branch, ph;
System.out.println("Enter Usn\n");
usn = scanner.next();
System.out.println("Enter Name\n");
name = scanner.next();
System.out.println("Enter Branch\n");
branch = scanner.next();
System.out.println("Enter Phone\n");
ph = scanner.next();
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
/*
1.b. Write a Java program to implement the Stack using arrays. Write
Push(), Pop(), and
Display() methods to demonstrate its working.
*/
import java.util.Scanner;
class Stack {
private int arr[], top, size;
class Main {
while (true) {
System.out.println("\nStack Operations");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter integer element to push");
stack.push(scanner.nextInt());
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
System.exit(0);
}
}
}
}
import java.util.Scanner;
class Staff {
private String staffId;
private String name;
private int phone;
private float salary;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.StringTokenizer;
class Customer {
String name;
String dob;
void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Name and DoB");
String input = scanner.nextLine();
StringTokenizer stringTokenizer = new StringTokenizer(input,
",");
try {
name = stringTokenizer.nextToken().trim();
dob = stringTokenizer.nextToken().trim();
} catch (NoSuchElementException e) {
System.out.println("Invalid Format");
System.exit(0);
}
}
void display() {
StringTokenizer stringTokenizer = new StringTokenizer(dob,
"/");
try {
String dd = stringTokenizer.nextToken().trim();
String mm = stringTokenizer.nextToken().trim();
String yy = stringTokenizer.nextToken().trim();
System.out.println(stringJoiner.toString());
} catch (NoSuchElementException e) {
System.out.println("Invalid Format");
System.exit(0);
}
}
}
class Main {
static Customer customer;
import java.lang.Exception;
import java.util.Scanner;
class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers");
int a = scanner.nextInt();
int b = scanner.nextInt();
if (b != 0) {
System.out.println("a/b = " + (((float) a) / b));
} else {
throw new Exception("b is zero");
}
}
}
/*
BMSIT&M – Department of CSE Subject Code:18CSL47 Page 17
3.b. Write a Java program that implements a multi-thread application
that has three threads. First thread generates a random integer for
every 1 second; second thread computes the square of the number and
prints; third thread will print the value of cube of the number.
*/
import java.util.Random;
@Override
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
number = random.nextInt(10) + 1;
System.out.println("\nRandom Number: " + number);
Main.square.interrupt();
Main.cube.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Main {
static Thread generator;
static Thread square;
static Thread cube;
square.start();
cube.start();
generator.start();
}
}
import java.util.Random;
import java.util.Scanner;
class QuickSort {
static int comparisons = 0;
i = i + 1;
}
j = j - 1;
}
if (i < j) {
comparisons += 1;
interchange(i, j);
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
System.out.println("Quick Sort");
System.out.println("1. Best/Average Case");
System.out.println("2. Worst Case");
int ch = scanner.nextInt();
switch (ch) {
case 1:
Random random = new Random();
for (int i = 0; i < n; i++) {
arr[i] = random.nextInt();
}
break;
case 2:
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
break;
}
System.out.println("Sorted Array");
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
import java.util.Random;
import java.util.Scanner;
class MergeSort {
static int comparisons = 0;
t_arr[k] = arr[i];
i++;
} else {
comparisons += 1;
t_arr[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) {
// Put remaining elements from left subpart (if any) to
temporary array.
t_arr[k] = arr[i];
i++;
k++;
}
while (j <= high) {
// Put remaining elements from right subpart (if any) to
temporary array.
comparisons += 1;
t_arr[k] = arr[j];
j++;
k++;
}
for (k = 0; k < n; k++) {
// Copy Elements from temporary array to original array.
comparisons += 1;
arr[low + k] = t_arr[k];
}
}
/*
As per VTU textbooks descending order of elements is
worst case
break;
}
// }
import java.util.Scanner;
class Knapsack {
private int[] weight, profit;
private int capacity, n;
Knapsack() {
Scanner scanner = new Scanner(System.in);
void fill() {
int[][] K = new int[n + 1][capacity + 1];
int i = n, j = capacity;
import java.util.Scanner;
class Knapsack {
Knapsack() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of Items");
int n = scanner.nextInt();
weight = new double[n];
profit = new double[n];
ratio = new double[n];
solnVector = new double[n];
int getNext() {
int index = -1;
double highest = 0;
void fill() {
double currentWeight = 0;
double currentProfit = 0;
if (item == -1) {
break;
}
System.out.println();
System.out.println("Maximum Profit is: " + currentProfit);
System.out.print("Solution Vector: ");
for (int i = 0; i < solnVector.length; i++) {
System.out.print(solnVector[i] + " ");
}
System.out.println();
}
import java.util.Scanner;
class Main {
visited[src - 1] = true;
visited[unvis] = true;
return dist;
}
}
import java.util.Arrays;
import java.util.Scanner;
class Edge {
int src;
int dest;
int weight;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of Vertices");
int n = scanner.nextInt();
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
edges[k] = new Edge(i, j, adj[i][j]);
k++;
}
}
sort(edges);
int minCost = 0;
System.out.println();
System.out.println("Minimum Cost of Spanning Tree: " +
minCost);
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
visited[srcVertex - 1] = true;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
import java.util.ArrayList;
import java.util.Scanner;
class Main {
static int[][] graph;
static int n, src;
path[0] = src - 1;
path[n] = src - 1;
System.out.print("Path: ");
for (int i = n; i >= 0; i--) {
System.out.print((path[i] + 1) + " ");
}
System.out.println();
}
// ///////
// Output:
//
// Enter number of cities
// 4
// Enter Adjacency Matrix
// 0 10 15 20
// 5 0 9 10
// 6 13 0 12
// 8 8 9 0
// Enter Source City
// 1
// Total Cost: 35
// Path: 1 2 4 3 1
import java.util.Scanner;
class Main {
static int[] arr;
static int count;
if (count == 0) {
System.out.println("No solution");
}
}
// ///////
// Output:
//
// Enter n value
// 5
// Enter Elements of Set in Increasing Order
// 1 2 5 6 8
// Enter Total Sum value
// 9
// Solution: 1 2 6
// Solution: 1 8
import java.util.Scanner;
class Hamiltonian {
static int[][] graph;
static int[] soln;
static int n, count = 0;
if (count == 0) {
System.out.println("No Hamiltonian Cycle");
}
}