Professional Documents
Culture Documents
LABORATORY MANUAL
Objectives
To provide quality education and groom top-notch professionals, entrepreneurs and
leaders for different fields of engineering, technology and management.
To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research in
areas of social relevance, and develop the institute as a center of excellence.
To develop academic, professional and financial alliances with the industry as well
as the academia at national and transnational levels.
To cultivate strong community relationships and involve the students and the staff in
local community service.
To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.
Vision
Development of academically excellent, culturally vibrant, socially responsible
and globally competent human resources.
Mission
To keep pace with advancements in knowledge and make the students competitive and
capable at the global level.
To create an environment for the students to acquire the right physical,
intellectual, emotional and moral foundations and shine as torchbearers of
tomorrow's society.
To strive to attain ever-higher benchmarks of educational excellence.
Department of Computer Science & Engineering
PO2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles ofmathematics,
natural sciences, and engineering sciences.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)
1. Demonstrate understanding of the principles and working of the hardware
and software aspects of Embedded Systems.
2. Use professional Engineering practices, strategies and tactics for the development,
implementation and maintenance of software.
3. Provide effective and efficient real time solutions using acquired knowledge in various
domains.
Program Educational Objectives (PEOs):
1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment,
higher learning and R&D.
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 superclass called Staff with details as StaffId, 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 <name,
dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer 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 andprints; third thread will print the value of cube of the number.
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.
4. 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
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.
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program
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.
CHAPTER 1
INTRODUCTION
Need for studying algorithms
Theoretical importance
The study of algorithms is the concepts of computer science.
It is a standard set of important algorithms, they further our analytical skills& help us
in developing new algorithms for required applications
Algorithm
An algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for
obtaining a required output for any legitimate input in a finite amount of time.
In addition, all algorithms must satisfy the following criteria:
1. Input: Each algorithm should have zero or more inputs. The range of
input for which algorithms works should be specified carefully.
2. Output: The algorithm should produce correct results. At least one quantity
has to be produced.
3. Definiteness: Each instruction should be clear and unambiguous.
4. Effectiveness: Every instruction should be simple and should transform the given Input
to the desired output. so that it can be carried out, in
5. Finiteness: If we trace out the instruction of an algorithm, then for all cases, the
algorithm must terminates after a finite number of steps.
Notion of algorithm
Problem
Algorithm
Input Output
“Computer”
• Sorting
It refers to the problem of re-arranging the items of a given list in ascending or descending
order. The various algorithms that can be used for sorting are bubble sort, selection sort, insertion
sort, quick sort, merge sort, heap sort etc.
• Searching
This problem deals with finding a value, called a search key, in a given set.
The various algorithms that can be used for searching are binary
search, linear search, hashing, interpolation search etc.
• String processing
This problem deals with manipulation of characters or strings, string matching,
search and replace, deleting a string in a text etc.
String processing algorithm such as string matching algorithms is used in the
design of assemblers and compliers.
• Graph problems
The graph is a collection of vertices and edges.
• Combinatorial problems
These problems are used to find combinatorial object such as permutation and
combinations.
Ex: travelling salesman problem, graph coloring problem etc
• Geometric problems
This problem deal with geometric objects such as points, curves, lines, polygon etc.
Ex: closest-pair problem, convex hull problem
• Numerical problems
These problems involving mathematical manipulations solving equations,
computing differentiations and integrations, evaluating various types of functions
etc.
Ex: Gauss elimination method, Newton-Rap son method
Fundamentals of data Structures
Since most of the algorithms operate on the data, particular ways of arranging the data
play a critical role in the design & analysis of algorithms.
A data structure can be defined as a particular way of arrangement of data.
The commonly used data structures are:
1. Linear data structures
2. Graphs
3. Trees.
4. Sets and dictionaries
2. Graphs
A data structure that consists of a set of nodes and a set of edges that relate the nodes
to each other is called a graph.
3. Tree
A tree is a connected acyclic graph that has no cycle.
Analysis of algorithms
Worst-case efficiency:
Efficiency (number of times the basic operation will be executed) for the worst case
input of size n. i.e. The algorithm runs the longest among all possible inputs of size n.
Best-case efficiency:
Efficiency (number of times the basic operation will be executed for the best case
input of size n. i.e. The algorithm runs the fastest among all possible inputs of size n.
Average-case efficiency:
Average time taken (number of times the basic operation will be executed) to solve all the
possible instances (random) of the input.
Asymptotic Notations
Asymptotic notation is a way of comparing functions that ignores constant factors
and small input sizes.
Three notations used to compare orders of growth of an algorithm’s basic operation are:
O, Ω, θ notations.
Big-oh notation:
A function t(n) is said to be in O(g(n)),denoted t(n)€O(g(n)),if t(n) is bounded above by some
constant multiple of g(n) for all large n i.e., if there exist some positive constant c and some
Non negative integer n۪ 0 such that t (n)<=cg(n) for all n>= n0
Big-omega notation:
A function t(n) is said to be in Ω(g(n)),denoted t(n)€ Ω(g(n)),if t(n) is bounded below by
some constant multiple of g(n) for all large n i.e., if there exist some positive constant c and
some nonnegative integer n۪ 0 such that
t(n)>=cg(n) for all
n>=n0Big-theta notation:
A function t(n) is said to be in θ(g(n)),denoted t(n)€ θ(g(n)),if t(n) is bounded both
above and below by some positive constant multiple of g(n) for all large n i.e., if there exist
some positive constant c
1 constant
log n logarithmic
N linear
n log n n log n
n2 quadratic
n3 cubic
2n exponential
n! factorial
/* 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.*/
objectives:
This Program course enable students to :
Create Student object, Exception, BufferedReader inside a class
*/
Method second word first letter and class name first letter of first word are of uppercase,
variable declaration with normal syntax
*/
Algorithm:
//Input: Values for USN, name, branch and phone no
//Output: Displaying the details of n student objects
//Steps:
1) class “student” is created
2) Declare variables USN, Name, Branch, and Phone no.
3) a function “ read” is created that initialize the variables
4) a function “display” is created that prints the details
5) Multiple objects of “student” class calls the function “display” to print
the details contained in student class.
Program:
import java.util.Scanner;
public class student {
String USN;
String Name;
String branch;
int phone;
Void insertRecord (String reg,String name, String brnch, int ph)
{
USN=reg;
Name=name;
branch=brnch;
phone=ph;
}
Void displayRecord(){
int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=new student();
for(int j=0;j<n;j++)
String USN=sc.next();
String Name=sc.next();
String branch=sc.next();
s[j].insertRecord(USN,Name,branch,phone);
OUTPUT
Viva Questions :-
1. Define Class ?
2. What is array of object?
3 How to create object ?
/* 1b. Write a Java program to implement the Stack using arrays. Write Push(), Pop()
and Display() methods to demonstrate its working.*/
objectives:
This Program enable students to :
Learn the techniques of stacks and queues to solve problems.
Algorithm:
// Input : Elements to be pushed or popped from the Stack
// Output : pushed elements, popped elements, contents of stack
Steps:
1) A class created and variables are defined like max, arr[], top
2) A customized constructor of same class is used for initializing size,top
variables and the array[]
3) A function push() is created for pushing the elements into stack
4) A function pop() is created for popping the elements from stack
Program:
import java.util.Scanner;
{
int q=1;
Int ch=sc.nextInt();
switch(ch)
{
case 1:System.out.println("enter the element to be pushed");
int ele=sc.nextInt();
m.push(ele);
break;
case 2: int popele;
popele=m.pop();
System.out.println("the poped element is");
System.out.println(popele+" ");
break;
case 3:System.out.println("elements in the stack are");
m.display();
break;
case 4:q=0;
}
}
}
Output:
20
10
enter 1. Push 2.pop 3.display
enter your choice
1
enter the element to be pushed
30
enter 1. Push 2.pop 3.display
enter your choice
1
enter the element to be pushed
40
enter 1. Push 2.pop 3. Display
Outcomes:
On completion of this Program, the students are able to: Apply techniques of stacks
and queues to solve problems.
Viva Questions :
1. What is stack?
2. Difference between stack &queue?
3. What are major operation in stack?
4. What is array?
/* 2A. Design a super class called Staff with details as StaffId, 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. */
Objectives:
This Program enable students to :
Learn the inheritance concept
Algorithm:
//Input: StaffId, Name, Phone and Salary
Technical t2=new
Technical();
t2.readValue(); t2.skills();
Contract c1=new
Contract(); c1.readValue();
c1.period();
}
Program:
class Staff{
intstaffid,phone,salary;
String name;
public Staff(int id , int no, intsal, String na)
{ staffid=id;
phone=no;
salary=sal;
name=na;
}
void display()
{
System.out.println(" ");
System.out.println("Staff ID:"+ " "+ staffid);
System.out.println("Staff Phone number:" + " "+ phone);
System.out.println("Staff Salary:" +" "+ salary);
System.out.println("Staff Name:" +" "+ name);
}
}
class Teaching extends Staff
{ String domain; int
no_of_publications;
public Teaching(int id, int no, intsal, String na,Stringd,intnop)
{ super(id,no,sal,na);
domain=d;
no_of_publications=nop;
}
voidTdisplay()
{
System.out.println(" ");
Output:
-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 11
Staff Phone number: 998765434 Staff
Salary: 31000
Staff Name: Anil Domain :
CSE No_of_publications:10
-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 12
Staff Phone number: 996655546 Staff
Salary: 30000
Staff Name: AnuDomain :
ISE No_of_publications: 9
-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 13
Staff Phone number: 999933442 Staff
Salary: 32000
Staff Name: AnushaDomain :
EEE No_of_publications: 8
-- -- -- -- -- -- -- -- ---
Technical Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 21
Staff Phone number: 994433221 Staff
Salary: 22000
Staff Name: Kumar
Skills : C
-- -- -- -- -- -- -- -- ---
Outcomes:
On completion of this Program, the students are able to :
• Apply inheritance concept to solve theproblem.
Viva Questions:
1. Define superclass?
2. Define subclasses?
3. Define inheritance?
4. How to create object for superclasses?
5. How to use function from inherited class?
/* 2B. 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 <name, dd/mm/yyyy> and display as <name, dd, mm,
yyyy> using StringTokenizer class considering the delimiter character as “/”. */
//Output: name and date of birth displayed in <name, dd, mm, yyy> format
Steps:
1) A class named “customer” is created.
2) Variables are defined as name and date_of_birth
3) Values are read from the user of name and dat eof birth in dd/mm/yyy format
as strings. Scanner sc = new Scanner(System.in);
System.out.println("enter name");
String name=sc.next();
while (strToken.hasMoreElements())
System.out.println(name +strToken.nextElement());
}
6) The output is displayed then in the form of<name, dd,mm,yyy>
Program:
import java.util.Scanner;
importjava.util.StringTokenizer;
class customer
{
String name;
String date;
public void read()
{
Scanner input =new Scanner(System.in);
name=input.next();
date=input.next();
}
public void display()
{
System.out.print(name+",");
String delims="/";
StringTokenizerst=new StringTokenizer(date,delims);
while(st.hasMoreElements()){
System.out.print(st.nextElement()+",");
}
System.out.println();
}
for(int i=0;i<n;i++)
{
cus[i]=new customer();
cus[i].read();
}
for(int i=0;i<n;i++)
cus[i].display();
}
}
Output:
Develop a program that can be solved to store the irname and date_of_birthinside
Java class called Customer
Viva questions:
/* 3A. 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.*/
LearnInheritance,ExceptionconceptsandtoreadtwointegersaandbandtoCompute
a/b and print, when b is not zero. Raise an exception when b is equal to zero.
Algorithm:
// Input: values of two operand i.e a and b //
Output: a) answer displayed when b!=0
a =sc.nextInt();
b =sc.nextInt();
4) To calculate division is kept under try block try{
System.out.println(a/b);
Program:
Import java.util.Scanner;
class division
{
public static void main(String[] args)
{
int a,b,result;
Scanner input =new Scanner(System.in);
System.out.println("Input two integers");
a=input.nextInt();
b=input.nextInt();
try
{
result=a/b;
System.out.println("Result="+result);
}
catch(ArithmeticException e)
{
System.out.println("exception caught: Divide by zero error"+e);
}
Output:
Apply Exception concepts and Develop a program that can be solved to read two
integers a andb and to Compute a/b and print, when b is not zero. Raise an exception
when b is equal to zero.
Viva questions :
1. What is exception?
2. How to handle exception?
3. What is inheritance?
4. What is a best case efficiency?
/* 3B. Write a Java program that implements a multi-thread application that hash tree
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.*/ thread3.start();}}
Algorithm:
• // Input: Randomnumber
• //Output: square and cube of the number Steps:
1. Three threads arecreated.
2. Three classes RandomNumber, SquareGenerator and CubeGenerator are created
3. Class RandomNumber generates number and prints the
integer with thread t1
4. Nex tclassSquare Generator is called to generate square of the number
and print it with threadt2.
5. Atlast class CubeGenerator iscalled to generate cube of the number and
print it with threadt3.
Program:
import java.util.*;
for(int i=0;i<5;i++)
{
num=r.nextInt(100);
System.out.println("first thread generated number is “ +num);
Thread t2=new Thread (new second(num)); t2.start();
Thread t3=new Thread(new third(num)); t3.start();
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
OUTPUT:
Viva questions
/*4. Sort a given set of n integer elements using the Quicksort 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 n on 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.*/
Quick sort is one of the sorting algorithms working on the Divide and Conquer principle.
Quick sort works by finding an element, called pivot, in the given array and partitions the array
into three sub arrays such that
The left sub array contains all elements which are less than or equal to the pivot
The middle sub arrays contains pivot
The right sub array contains all elements which are greater than or equal to the pivot.
Quicksort is well-known sorting algorithms based on the divide and conquer technique.
After a partition has been achieved, A[s] will be in its final position in the sorted array, and we can
continue sorting the two sub arrays of the elements preceding and following A[s] independently.
Features:
• Developed by C.A.R.Hoare
• Efficient algorithm
ALGORITHM
Quicksort(A [l...r] )
// Sorts a subarray by quicksort
// Input : A subarray A [l...r] of A [0...n-1], defined by its left and right
indices l and r
// Output : The subarray A [l...r] sorted in nondecreasing order if l< r
ALGORITHM
Partition ( A [l...r] )
P ← A [l]
i←l;j←r+1
repeat
repeati ← i + 1 until A [i] >= p
repeatj ← j – 1 until A [j] <= p
swap ( A [i] , A [j] )
untili > = j
PROGRAM
import java.util.Random;
import java.util.Scanner;
if(low<high)
{
int s=partition(a,low,high);
sort(a,low,s-1); sort(a,s+1,high);
}
}
int[ ] a;
for( i=0;i<n;i++)
a[i]=generator.nextInt(20);
System.out.println("Array before sorting");
for( i=0;i<n;i++)
System.out.println(a[i]+" ");
Long StartTime=System.nanoTime();
quicksort m=new quicksort();
m.sort(a,0,n-1);
stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("Time taken to sort array is:"+elapseTime+"nano seconds”);
System.out.println("Sorted array is");
for(i=0;i<n;i++)
System.out.println(a[i]);
}}
OUTPUT:
Enter the array size 6
Array before sorting
17
17
12
2
10
3
Timetakentosortarrayis:16980nanoseconds
Sorted arrayis
2
3
10
12
17
17
Viva questions
1. How quick sort works
2. What is the worst-case behavior (number of comparisons) for quick sort?
3. Explain Divide and conquer method. Give an example
/* 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 n on 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.*/
Objectives:
This Program enable students to :
• Learn Merge sorting and searchingtechniques.
• Get exposed to Merge Sort algorithm designtechniques.
The basic operation in merge sort is comparison and swapping. Merge sort algorithm calls it
self recursively. Merge sort divides the array into sub arrays based on the position of the
elements whereas quick sort divides the array into sub arrays based on the value of the
elements.
ALGORITHM
Mergesort(A[0...n-1])
//Sorts array A[0...n-1] by recursive mergesort.
//Input an array A[0...n-1] of orderable elements.
// Output Array A[0...n-1] sorted in non-decreasing order.
If n>1
Copy A[0...(n/2)-1] to B[0...(n/2)-1]
Copy A[(n/2)...n-1], to C[0...(n/2)-1]
Mergesort(B[0...(n/2)-1])
Mergesort(C[0...(n/2)-1])
Merge(B,C,A)
ALGORITHM
Merge(B[0...p-1],C[0...q-1],A[0...p+q-1])
//Merges two sorted arrays into one sorted array
//Input : Arrays B[0...p-1] and C[0...q-1] both sorted
//Output : Sorted array A[0...p+q-1] of the elements of B and C
i←0;j←0;k←0;
Time Complexity
C (n) € Θ (nlogn)
Mergesortworksbydividingthegivenarrayintotwosubarraysofequalsize
The sorted sub array are then merged to get the solution for the originalarray
The principal shortcoming of mergesort is the linear amount of extra storage the algorithm
required.
Program :
import java.util.Random;
import java.util.Scanner;
public class Mergesort {
static int max=10000;
void merge( int[] array,int low, int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int[]resarray;
resarray=new int[max];
while(i<=mid&&j<=high)
{
if(array[i]<array[j])
{
resarray[k]=array[i];
i++;
k++;
}
else
{
resarray[k]=array[j];
j++;
k++;
}
}
while(i<=mid)
resarray[k++]=array[i++];
while(j<=high)
resarray[k++]=array[j++];
for(int m=low;m<=high;m++)
array[m]=resarray[m];
}
void Dept
sort( of CSE,
int[] ATMECE,
array,int MYSURU
low,int high) Page 41
{
if(low<high)
DAA LAB 18CSL47
{
int mid=(low+high)/2;
sort(array,low,mid);
sort(array,mid+1,high);
merge(array,low,mid,high);
}
}
public static void main(String[] args) {
int[] array;
int i;
System.out.println("Enter the array size");
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
array= new int[max];
Random generator=new Random();
for( i=0;i<n;i++)
array[i]=generator.nextInt(20);
System.out.println("Array before sorting");
for( i=0;i<n;i++)
System.out.println(array[i]+" ");
long startTime=System.nanoTime();
Mergesort m=new Mergesort();
m.sort(array,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("Time taken to sortseconds");
System.out.println("Sorted array is");
for(i=0;i<n;i++)
System.out.println(array[i]);
}}
OUTPUT 1:
Enter Max array size: 6
-- -- -- -- -- --
Time Complexity (ms) for n = 6 is :0.307211
Viva questions
1 What isMergesort
2 Explain Decrease/transfer and conquer method. Give anexample
3 DifferencebetweenDivideandconquermethod andDecrease/transferandconquermethod.
4 Sort the given elements using Mergesort 67 24 9 5 25 66 88 4990
6A). Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method
Learn the 0/1 Knapsack problem using Dynamic Programming method to implement in java
Given a knapsack with maximum capacity W, and a set S consisting of n items , Each item i
has some weight wiand benefit value bi (all wi , bi and W are integer values)
ALGORITHM
//Input: (n items, W weight of sack) Input: n, wi,,, vi and W – all integers
//Output: V(n,W)
Steps:
Repeat for i = 0 to n
set V(i,0) = 0
Repeat for j = 0 toW
Set V(0,j) =0
//complete remaining entries
PrintV(n,W)
PROGRAM
package knapsackdp;
import java.util.Scanner;
public class KnapsackDP {
public void solve(int[] wt, int[] val, int W, int N)
{
int i,j;
int[][] sol = new int[N + 1][W + 1];
for ( i = 0; i <= N; i++)
{
for ( j = 0; j <= W; j++)
{
if(i==0||j==0)
sol[i][j]=0;
else if(wt[i]>j)
sol[i][j]=sol[i-1][j];
else
sol[i][j]=Math.max((sol[i-1][j]), (sol[i - 1][j - wt[i]] + val[i]));
}
}
System.out.println("The optimal solutionis"+sol[N][W]);
int[] selected = new int[N + 1];
for(i=0;i<N+1;i++)
selected[i]=0;
i=N;
j=W;
while (i>0&&j>0)
{
if (sol[i][j] !=sol[i-1][j])
{
selected[i] = 1;
j = j - wt[i];
}
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
KnapsackDP ks = new KnapsackDP();
System.out.println("Enter number of elements ");
int n = scan.nextInt();
int[] wt = new int[n + 1];
int[] val = new int[n + 1];
System.out.println("\nEnter weight for "+ n +"elements");
for (int i = 1; i <= n; i++)
wt[i] = scan.nextInt();
System.out.println("\nEnter value for "+ n +"elements");
for (int i = 1; i <= n; i++)
val[i] = scan.nextInt();
System.out.println("\nEnter knapsack weight ");
int W = scan.nextInt();
ks.solve(wt, val, W, n);
}
}
OUTPUT :
4
Enter number of elements:
3
Enter Weights for 3 elements:
2
1
1
Enter Profits for 3 elements:
4
5
2
Enter knapsack weight
3
2
1
Optimal solution = 11
BUILD SUCCESSFUL (total time: 35 seconds)
Solve0/1KnapsackproblemusingDynamicProgrammingmethodtoimplementinjava
Viva questions
1. What is dynamicprogram?
2. Knapsack problem can be solved by using whichmethod.
3. Whatisthedifferencebetweendynamicmethodandgreedymethodprograming
Techniques ?
/*6B. Implement in Java, the 0/1 Knapsack problem using Greedy method.*/
Learn the 0/1 Knapsack problem using Greedy method to implement in java
ALGORITHM:
Knapsack (i, j )
//Input: A nonnegative integer i indicating the number of the first items being considered and a non
negative integer j indicating the Knapsack’s capacity.
//Note: Uses as global variables input arrays Weights [1...n ], Values [ 1… n ] and table
V [0…n, 0…W ] whose entries are initialized with -1’s except for row 0 and
column 0 initialized with 0’s.
if V [i, j] < 0
else
value = max ( Knapsack ( i -1, j ),
values[I] + Knapsack ( i-1, j-Weights[i] ) )
V[i j] = value
return V [ i, j ]
Efficiency:
• O( n * W)
Impor tjava.util.Scanner;
Consider a matrix of different weights (starting from zero total weight ) and different capacity
(starting from zero to given knapsack capacity) indicating the profit value.
When knapsack capacity is less than weight then profit is the previous profit
profit by current object+ profit by previous object for current weight difference)
PROGRAM
package greedy;
import java.util.Scanner;
public class Greedy {
public static void main(String[] args)
{
int i,j=0,max_qty,m,n;
float sum=0,max;
Scanner sc = new Scanner(System.in);
int array[][]=new int[2][20];
System.out.println("Enter no of items");
n=sc.nextInt();
System.out.println("Enter the weights of each items");
for(i=0;i<n;i++)
array[0][i]=sc.nextInt();
System.out.println("Enter the values of each items");
for(i=0;i<n;i++)
array[1][i]=sc.nextInt();
System.out.println("Enter maximum volume of knapsack :");
max_qty=sc.nextInt();
m=max_qty;
while(m>=0)
{
max=0;
for(i=0;i<n;i++)
{
if(((float)array[1][i])/((float)array[0][i])>max)
{
max=((float)array[1][i])/((float)array[0][i]);
j=i;
}
}
if(array[0][j]>m)
{
OUTPUT:
Viva questions :
1. What is dynamicprogram?
2. Knapsack problem can be solved by using whichmethod.
3. Whatisthedifferencebetweendynamicmethodandgreedymethodprograming
Techniques?
* 7.Fromagivenvertexinaweightedconnectedgraph,findshortestpathstoothervertices using
Dijkstra's algorithm. Write the program inJava.*/
Dijkstra’s algorithm finds shortest paths to a graph’s vertices in order of their distance from a
given source. First, it finds the shortest path from the source to a vertex nearest to it, then to a
second nearest and so on.
sv
dv dv dv
Aim:
Algorithm:
// Input: A weighted connected graph G ={V,E}, source s
• Print weightedgraph
• Initializedistancefromsourceforallverticesasweightbetweensourcenodeandother
vertices, i, and none intree
// initial condition
• Forallothervertices,dv[i]=wt_graph[s,i],TV[i]=0,prev[i]=0dv[s]=0,prev[s]=s// source
vertex
{ minm = dv [k]
j=k
PROGRAM
Import java.util.Scanner;
public class Dijkstra {
int d[ ]=new int[10];
int p[ ]=new int[10];
int visited[ ]=new int[10];
}
void path(intv,int s)
{
if(p[v]!=-1)
path(p[v],s);
if(v!=s)
System.out.print("->"+v+" ");
}
void display(ints,intn)
{ int i;for(i=0;i<n;i++)
{
if(i!=s){
System.out.print(s+" ");
path(i,s);
if(i!=s)
System.out.print("="+d[i]+" ");
System.out.println();
}
}
public static void main(String[] args) {
inti,j,n,s;
System.out.println("enter the number of vertices");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
System.out.println("enter the weighted matrix");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=sc.nextInt();
System.out.println("enter the source vertex");
s=sc.nextInt();
Dijkstratr=new Dijkstra();
tr.dijk(a,s,n);
System.out.println("the shortest path between source"+s+"to remaining vertices are");
tr.display(s,n);
sc.close();
}}
Output:
0 ->1 =3
0 ->1 ->2=7
0 ->1 ->3=5
0 ->1 ->3 ->4 =9
Viva questions
2. Application of DijkstrasAlgorithm.
/* 8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm. Implement the program in Java language. */
Kruskal’s algorithm looks at a minimum spanning three for a weighted connected graph
G=(V,E) as an acyclic sub graph with V-1 edges for which the sum of the edge weights is the
smallest.
The algorithm begins by sorting the graph’s edges in increasing order of their weights. Then
starting with the empty sub graph, it scans this sorted list adding the next edge on the list to the
current sub graph if such an inclusion does not create a cycle and simply skipping the edge
otherwise.
When you select a minimum weight path, it will have source and destination vertices. These
twoverticesshouldnothavesameancestororparent.Ifboththeverticeshavethesameorigin, then it is
a cyclicgraph.
DCBA
Here CD is the current edge. Vertex C is the parent of D. But C has parent vertex called B. For
B also a parent called A. According to kruskal’s algorithm, We should add all previous path to
the current path.Then here vertex A becomes the parent of vertex D.
Aim:
Kruskal's Algorithm for computing the minimum spanning tree is directly based on the generic
MST algorithm. It builds the MST in forest. Prim's algorithm is based on a generic MST algorithm.
It uses greedy approach.
Algorithm:
Kruskal's Algorithm
Start with an empty set A, and select at every stage the shortest edge that has not been chosen or
rejected, regardless of where this edge is situated in graph.
• Ontheotherhand,ifanedge(u,v)connectstwoverticesinthesametree,thenedge(u,
v) is discarded.
PROGRAM
import java.util.Scanner;
void union(inti,int j)
{
if(i<j)
parent[i]=j;
else
parent[j]=i;
}
voidkrkl(int[][]a, int n)
{
int u=0,v=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]<min&&i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]);
sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=99;
}
}
}
Output:
Enter the number of vertices of the graph 6
Enter the wieghted matrix
0 3 99 99 6 5
3 0 1 99 994
99 1 0 6 994
99 99 6 0 85
6 99 99 8 02
544520
(2,3)=1
(5,6)=2
(1,2)=3
(2,6)=4
(4,6)=5
The cost of minimum spanning tree = 15
Viva questions
9 .FindMinimumCostSpanningTreeofagivenundirectedgraphusingPrim'salgorithm.
Implement the program in Javalanguage.
• Prim'salgorithmhasthepropertythattheedgesinthesetAalwaysformasingletree.
• Webegin with vertexvinagivengraph G=(V,E),defining the initial set of
vertices A.
• ThevertexuisbroughtintoA.Thisprocessisrepeateduntilaspanningtreeisformed.
PROGRAM
sum=sum+min; k++;
System.out.println(u+"->"+v+"="+min);
}
for(i=1;i<=n;i++)
if(sol[i]==0) flag=1;
if(flag==1)
System.out.println("No spanning tree");
Else
System.out.println("The cost of minimum spanning tree is"+sum);
sc.close();
}
}
Output:
Enter the number of vertices 6
Enter the weighted graph 0
3 99 99 6 5
3 0 1 99 994
99 1 0 6 994
99 99 6 0 85
6 99 99 8 02
544520
Enter the source vertex1
1->2=3
2->3=1
2->6=4
6->5=2
6->4=5
The cost of minimum spanning tree is15
Viva questions
/*10A. Write Java programs to implement All-Pairs Shortest Paths problem using
Floyd's algorithm.*/
The following formula can be used to find the each element in the distance matrix.
d(k) min{d(k-1) , d(k-1) + d(k-1 ) } where k>=1,d(0)w
ij ij ik kj ij ij
ALGORITHM
Algorithm Floyd(W[1..n,1..n])
//ImplementsFloyd’salgorithm
D(0)w
fork1 to n do
fori1 to n do
forj1 to n do
D(k)min{d(k-1)[i,j], d(k-1)[i,k]+d(k-1)[k,j]}
ReturnD(n)
PROGRAM
importjava.util.Scanner;
public class floyd {
voidflyd(int [ ] [ ] w,int n)
{
inti,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=Math.min(w[i][j], w[i][k]+w[k][j]);
}
Output:
enter the number of vertices 4
Enter the weighted matrix
0 99 399
2 0 9999
99 7 0 1
6 99 99 0
The shortest path matrix is
0 10 3 4
2 0 56
7 7 01
6 16 9 0
Outcomes:OnCompletionoftheseProgramenablestudentsto:
Viva questions
10 B.WriteJavaprogramstoimplementTravellingSalesPersonproblemusingDynamic
programming.*/
Objectives: This Program enable students to :
Aim:
Travelling Sales Person problem: Given a set of cities and distance between every pair of cities,
the problem is to find the shortest possible route that visits every city exactly once and returns to
the starting point. Here we know that Hamiltonian Tour exists (because the graph is complete)
and in fact many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle.
For example, consider the graph shown in above figure. A TSP tour in the graph is 1 -2-4-3-1.
The cost of the tour is 10+25+30+15 which is 80.
PROGRAM
package tsp;
import java.util.Scanner;
class TSPExp {
int weight[][],n,tour[],finalCost;
final int INF=1000;
TSPExp()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes :=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of"+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
public int COST(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
Dept of CSE, ATMECE, MYSURU
Page 72
DAA LAB 18CSL47
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
}
}
return min;
}
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)//considers each node of inputSet
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int
temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
OUTPUT :
******* TSP DYNAMIC PROGRAMMING
******* Enter number of cities:
3
Enter Cost matrix:
1
2
3
4
5
6
7
8
5
Minimum Tour Cost: 15
Tour:
0 -> 1 -> 2 -> 0
Viva questions
Aim:
Subset is a pair(S,t),whereS={x1,x2, ............................................................. ,xn} is a set of
positive integers and t (the target) is a positive integer. The decision problem asks for a subset of
S whose sum is as large as possible, but not larger than t.
• Algorithm:
• accept n: no of items inset
• If (s + s[k] + s[k+1]<=d)
thenSumOfSum(s+ s[k],k+1,r–s[k])
//Generate right child i.e. element k absent
• If(s+r-s[k]>=d)AND(s+ s[k+1])<=d
THEN {x[k]=0;
PROGRAM
importjava.util.Scanner;
import static java.lang.Math.pow;
if(d==sum)
{
System.out.print("Subset={");
present=1;
for(j=1;j<=n;j++)
if(x[j]==1)
System.out.print(a[j]+",");
System.out.print("}="+d);
System.out.println();
} }}
if(present==0)
System.out.println("Solution does not exists");
Output:
Viva questions
12. DesignandimplementthepresenceofHamiltonianCycleinanundirectedGraphG of
nvertices.*/
objectives: This Program enable students to :
Output:
An array path[V] that should contain the Hamiltonian Path. path[i] should represent theith
vertexintheHamiltonianPath.ThecodeshouldalsoreturnfalseifthereisnoHamiltonian Cycle
in thegraph.
Backtracking Algorithm
Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex
1.Beforeadding avertex,checkforwhetheritisadjacenttothepreviously addedvertexand
notalreadyadded.Ifwefindsuchavertex,weaddthevertexaspartofthesolution.Ifwedo not find a
vertex then we returnfalse.
PROGRAM
importjava.util.*;
classHamiltoniancycle
{
privateintadj[][],x[],n; public
Hamiltoniancycle()
{
Scanner src = new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=src.nextInt();
x=new int[n]; x[0]=0;
for (int i=1;i<n; i++) x[i]=-1;
adj=new int[n][n];
System.out.println("Enter the adjacency matrix");
for (int i=0;i<n; i++)
for (int j=0; j<n; j++) adj[i][j]=src.nextInt();
}
}
classHamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycleobj=new Hamiltoniancycle();
obj.getHCycle(1);
}
}
Output:
Solution:
1265341
Solution:
1265431
Solution:
1326541
Solution:
1345621
Solution:
1435621
Solution:
1456231
Viva questions
What is N-Queensproblem?
Difference between ‘Branch and bound’ and ‘Backtracking’algorithm.
What is the time complexity of N-queensproble