You are on page 1of 93

ATME COLLEGE OF ENGINEERING

13thKM Stone, Bannur Road, Mysore - 560 028

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(ACADEMIC YEAR 2019-20)

LABORATORY MANUAL

SUBJECT: DESIGN & ANALYSIS OF ALGORITHM LAB


SUB CODE: 18CSL47
SEMESTER: IV
SCHEME: 2018
INSTITUTIONAL MISSION AND VISION

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

Vision of the Department


 To develop highly talented individuals in Computer Science and Engineering to deal with

real world challenges in industry, education, research and society.

Mission of the Department


 To inculcate professional behavior, strong ethical values, innovative research capabilities
and leadership abilities in the young minds & to provide a teaching environment that
emphasizes depth, originality and critical thinking.

 Motivate students to put their thoughts and ideas adoptable by industry or to


pursue higher studies leading to research.

Program outcomes (POs)

Engineering Graduates will be able to:

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

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.

PO3. Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

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.

PO10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

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.

2. Gain technical knowledge, skills and awareness of current technologies of computer


science engineering and to develop an ability to design and provide novel engineering
solutions for software/hardware problems through entrepreneurial skills.

3. Exposure to emerging technologies and work in teams on interdisciplinary projects


with effective communication skills and leadership qualities.

4. Ability to function ethically and responsibly in a rapidly changing environment by


applying innovative ideas in the latest technology, to become effective professionals in
Computer Science to bear a life-long career in relate dare as.
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY
(Effective from the academic year 2018 -2019)
SEMESTER – IV
Subject Code 18CSL47 CIE Marks 40
Number of Contact Hours/Week 0:2:2 SEE Marks 60
Total Number of Lab Contact Hours 36 Exam Hours 3 Hrs
Credits – 2
Course Learning Objectives: This course (18CSL47) will enable students to:
 Design and implement various algorithms in JAVA
 Employ various design strategies for problem solving.
 Measure and compare the performance of different algorithms.
Descriptions (if any):
 Design, develop, and implement the specified algorithms for the following problems using Java
language under LINUX /Windows environment. Netbeans / Eclipse IDE tool can be used for
development and demonstration.
Programs List:
1.
a. Create a Java class called Studentwith the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create nStudent objects and print the USN, Name, Branch, and
Phoneof 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 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.

10. Write Java programs to


(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.

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.

Laboratory Outcomes: The student should be able to:


 Design algorithms using appropriate design techniques (brute-force, greedy, dynamic
programming, etc.)
 Implement a variety of algorithms such assorting, graph related, combinatorial, etc., in a high
level language.
 Analyze and compare the performance of algorithms using language features.
 Apply and implement learned algorithm design techniques and data structuresto solve real-world
problems.
Conduct of Practical Examination:
 All laboratory experiments, excluding the first, are to be included for practical examination.
 Experiment distribution
 For questions having only one part: Students are allowed to pick one experiment from the lot and
are given equal opportunity.
o For questions having part A and B: Students are allowed to pick one experiment from
part A and one experiment from part B and are given equal opportunity.
 Change of experiment is allowed only once and marks allotted for procedure part to be made
zero.
 Marks Distribution (Subjected to change in accoradance with university regulations)
e) For questions having only one part – Procedure + Execution + Viva-Voce: 15+70+15 =
100 Marks
f) For questions having part A and B
i. Part A – Procedure + Execution + Viva = 4 + 21 + 5 = 30 Marks
 Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks
CONTENTS

Sl.No. Particulars Page No


Introduction 1
1a) Create a Java class called Student with the following 7
details Given
1b) Write a Java program to implement the Stack using 11
arrays.
2a) Design a super class called Staff with details as Staff Id, 15
Name, Phone, and Salary. Extend this class
2b) Write a Java class called Customer to store their name 23
and date_of_birth. The date_of_birth format
3a) Write a Java program to read two integers a and b. 27
Compute a/b and print, when b is not zero. Raise an
exception when b is equal to zero
3b) Write a Java program that implements a multi-thread 30
application that has three threads
4 Sort a given set of n integer elements using Quick Sort
34
method and compute its time complexity.
5 Sort a given set of n integer elements using Merge Sort 39
method and compute its time complexity.
6 Implement in Java, the 0/1 Knapsack problem using (a) 44
Dynamic Programming method (b) Greedy method.

7 From a given vertex in a weighted connected graph, find 53


shortest paths to other vertices using Dijkstra's
algorithm. Write the program in Java.

8 Find Minimum Cost Spanning Tree of a given connect 59


undirected graph using Kruskal’s algorithm.
9 Find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm 64
10 Write Java programs to
(a) Implement All-Pairs Shortest Paths problem using
Floyd's algorithm. 68
(b) Implement Travelling Sales Person problem using
Dynamic programming.

11 Design and implement in Java to find a subset of a given 75


set S ={Sl,S2, ....... ,Sn} of n positive
12 Design and implement in Java to find all Hamiltonian 79
Cycles in a connected undirected Graph G of n vertices
using backtracking principle
DAA LAB 18CSL47

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”

Dept of CSE, ATMECE, MYSURU Page 1


DAA LAB 18CSL47

Fundamentals of Algorithmic problem solving


• Understanding the problem
• Ascertain the capabilities of the computational device
• Exact /approximate solution.
• Decide on the appropriate data structure
• Algorithm design techniques
• Methods of specifying an algorithm
• Proving an algorithms correctness
• Analyzing an algorithm

Important Problem Types of different categories

• 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.

 Ex: graph traversal problems, topological sorting etc

Dept of CSE, ATMECE, MYSURU Page 2


DAA LAB 18CSL47

• 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

1. Linear data structures


The most common linear data structures are arrays and linked lists.
Arrays: Is a collection of homogeneous items. An item’s place within the collection is
called an index.
Linked list: finite sequence of data itemsi.e.it is a collection of data items in a certain order.

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.

Dept of CSE, ATMECE, MYSURU Page 3


DAA LAB 18CSL47

 Undirected graph: A graph in which the edges have no direction


 Directed graph(Digraph):A graph in which each edge is directed from one
vertex to another (or the same)vertex.

3. Tree
A tree is a connected acyclic graph that has no cycle.

4. Sets and dictionaries


 A set is defined as an unordered collection of distinct items called an element of the set
 Dictionary is a data structure that implements searching, adding of objects

Analysis of algorithms

Analysis of algorithms means to investigate an algorithm’s efficiency with respect to


resources:
• Running time (time efficiency)
It indicates how fast an algorithm in question runs
• Memory space (space efficiency)
It deals with the extra space the algorithm requires

Theoretical analysis of time efficiency


Algorithm efficiency depends on the input size n. And for some algorithms efficiency
depends on type of input.
We have best, worst & average case efficiencies

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.

Dept of CSE, ATMECE, MYSURU Page 4


DAA LAB 18CSL47

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-oh notation t(n)€O(g(n)) Big-omega notation t(n)€Ω,(g(n))

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

Dept of CSE, ATMECE, MYSURU Page 5


DAA LAB 18CSL47

c2g(n)<=t(n)<=c1g(n) for all n>= n0

Big-theta notation t(n)€θ(g(n))

Basic Asymptotic Efficiency classes:

1 constant

log n logarithmic

N linear

n log n n log n

n2 quadratic

n3 cubic

2n exponential

n! factorial

Dept of CSE, ATMECE, MYSURU Page 6


DAA LAB 18CSL47

/* 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.

Dept of CSE, ATMECE, MYSURU Page 7


DAA LAB 18CSL47

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(){

System.out.println(USN+" "+Name+" "+branch+" "+phone);

Public static void main(String args[]){

student s[]=new student [100];

Scanner sc=new Scanner(System.in);


System.out.println("enter the number of students");

int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=new student();
for(int j=0;j<n;j++)

System.out.println("enter the USN,Name,branch,phone");

String USN=sc.next();
String Name=sc.next();
String branch=sc.next();

Dept of CSE, ATMECE, MYSURU Page 9


DAA LAB 18CSL47
int phone=sc.nextInt();

s[j].insertRecord(USN,Name,branch,phone);

for(int m=0;m<n;m++){ s[m].displayRecord();}}}}

OUTPUT

Enter the number of students 2


Enter the usn,name,branch,phone
1 Monika cse 93411
Enter the usn,name,branch,phone
12 gowda cse 9785

Students details are

1 Monika cse 93411


12 gowda cse 9785

Outcomes: On completion of this Program, the students are able to :


 Creating Student Class, object

Viva Questions :-
1. Define Class ?
2. What is array of object?
3 How to create object ?

Dept of CSE, ATMECE, MYSURU Page 10


DAA LAB 18CSL47

/* 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

5) A function display() is created for displaying the elements in the stack:


6) A Boolean function is created to check whether stack is empty or full:
Boolean

Dept of CSE, ATMECE, MYSURU Page 11


DAA LAB 18CSL47

Program:

import java.util.Scanner;

public class stack{ final int


max=100;
int s[ ]=new int[max]; int top=-1;
void push(int ele)
{
if(top>=max-1)
System.out.println("stack overflow");
else
s[++top]=ele;
}
int pop()
{
int z=0;
if(top==-1)
System.out.println("stack underflow");
Else
z=s[top--];
return z;
}
void display()
{
if(top==-1)
System.out.println("stack empty");
else
{
for(int i=top;i>-1;i--)
System.out.println(s[i]+" ");
}

Dept of CSE,ATMECE,MYSURU Page11


DAA LAB 18CSL47

Public static void main (String args[])

{
int q=1;

stack m = new stack();


System.out.println("program to perform stack operations");

Scanner sc=new Scanner(System.in);


while(q!=0){
System.out.println("enter 1. push 2.pop 3. display ");
System.out.println("enter your choice");

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;

}
}
}

Dept of CSE, ATMECE, MYSURU Page 12


DAA LAB 18CSL47

Output:

program to perform stack operations


enter 1. Push 2.pop 3.display
enter your choice
1
enter the element to be pushed
10
enter 1. Push 2.pop 3.display
enter your choice
1
enter the element to be pushed
20
enter 1. Push 2.pop 3.display
enter your choice
3
Elements in the stack are

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

Dept of CSE, ATMECE, MYSURU Page 13


DAA LAB 18CSL47

enter your choice


3
elements in the stack
40
30
20
10

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?

Dept of CSE, ATMECE, MYSURU Page 14


DAA LAB 18CSL47

/* 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

//Output: displaying the three staff objects of each class.


Steps:

1) A class created named“staff”.


2) Declared variables are StaffId,Name,PhoneNo,Salary
3) Constructor is used to initialize the values of these variables.

4) To read values from console : readValues() {

Scanner s1 new Scanner(System.in);


// Scanner class is defined in library in “java.util.Scanner” package. We need to
import //this package in our program for successful compilation.

System.out.println(“enter staff id”);


StafId= (s1.next());
System.out.println(“enter name”);
name= (s1.next());
System.out.println(“enter phone”);
phone= (s1.next());
System.out.println(“enter salary”);
salary= (s1.nextInt());
}

5) Subclass “teaching” is created that inherits superclass“staff”.


6) Two functions are defined inside “teaching” class. They are “domain” and
“publications”.Thesefunctionsprintthedomainofparticularstaffandno.of
publications by him respectively.

7) A class is created “technical” that inherits super class“staff”.


8) Onefunctionisdefinedunder“technical”classnamed“skills”.Thisfunctions
displays the skills of particularstaff.

Dept of CSE, ATMECE, MYSURU Page 15


DAA LAB 18CSL47

9) A class is created named “contract” that inherits the super class“staff”


10) Onefunctionisdefinedunder“contract”classnamed“period”.Thisfunction
displayed the contract period of the particular staff.
11) Objects are made of each subclass and functions are called.
Public static void main(String args[])

Teaching t1= new


Teaching();
t1.readValue();
t1.domain();
t1.publications():

Technical t2=new
Technical();
t2.readValue(); t2.skills();
Contract c1=new
Contract(); c1.readValue();
c1.period();
}

Dept of CSE, ATMECE, MYSURU Page 16


DAA LAB 18CSL47

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(" ");

Dept of CSE, ATMECE, MYSURU Page 17


DAA LAB 18CSL47

System.out.println("Teaching Staff Details");


super.display();
System.out.println("Domain :" +" "+domain);
System.out.println("No_of_publications:"+" "+no_of_publications);
}
}
class Technical extends Staff
{ String skills;
public Technical(int id , int no, intsal, String na,Stringsk){ super(id,no,sal,na);
skills=sk;
}
voidTedisplay(){
System.out.println(" ");
System.out.println("Technical Staff Details");
super.display();
System.out.println("Skills :" + " "+skills);
}
}

class Contract extends Staff{ int period;


public Contract(int id , int no, intsal, String na,intpd){ super(id,no,sal,na);
period=pd;}
voidCdisplay(){
System.out.println(" ");
System.out.println("Contract Staff Details");
super.display();
System.out.println("ContractPeriod:" + " "+period + "years");
}
}
public class Multilevel{
public static void main(String args[]){

Dept of CSE, ATMECE, MYSURU Page 18


DAA LAB 18CSL47

Teaching t1=new Teaching(11,998765434,31000,"Anil","CSE",10); Teaching


t2=new Teaching(12,996655546,30000,"Anu","ISE",9);
Teachingt3=newTeaching(13,999933442,32000,"Anusha","EEE",8);
t1.Tdisplay();
t2.Tdisplay();
t3.Tdisplay();
Technicalte1=new Technical(21,994433221,22000,"Kumar","C");
Technicalte2=new Technical(22,998877665,28000,"Krisna","Java");
Technical te3=new Technical(23,991654321,33000,"Kiran","Java");
te1.Tedisplay();
te2.Tedisplay();
te3.Tedisplay();
Contract ct1=new Contract(31,998765434,35000,"Anil",3);
Contract ct2=new Contract(32,912345678,39000,"Meghana",2);
Contract ct3=new Contract(33,992233445,30000,"Uma",4);
ct1.Cdisplay();
ct2.Cdisplay();
ct3.Cdisplay();
}
}

Output:

-- -- -- -- -- -- -- -- ---
Teaching Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 11
Staff Phone number: 998765434 Staff
Salary: 31000
Staff Name: Anil Domain :
CSE No_of_publications:10

Dept of CSE, ATMECE, MYSURU Page 19


DAA LAB 18CSL47

-- -- -- -- -- -- -- -- ---
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
-- -- -- -- -- -- -- -- ---

Dept of CSE, ATMECE, MYSURU Page 20


DAA LAB 18CSL47

Technical Staff Details


-- -- -- -- -- -- -- -- ---
Staff ID: 22
Staff Phone number: 998877665 Staff
Salary: 28000
Staff Name: Krisna Skills
: Java
-- -- -- -- -- -- -- -- ---
Technical Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 23
Staff Phone number: 991654321 Staff
Salary: 33000
Staff Name: Kiran Skills
: Java
-- -- -- -- -- -- -- -- ---
Contract Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 31
Staff Phone number: 998765434 Staff
Salary: 35000
Staff Name: Anil

Contract Period: 3years


-- -- -- -- -- -- -- -- ---
Contract Staff Details
-- -- -- -- -- -- -- -- ---
Staff ID: 32
Staff Phone number: 912345678 Staff
Salary: 39000
Staff Name: Meghana
ContractPeriod: 2years-----

Dept of CSE, ATMECE, MYSURU Page 21


DAA LAB 18CSL47

Contract Staff Details


-- -- -- -- -- -- -- -- ---
Staff ID: 33
Staff Phone number: 992233445 Staff
Salary: 30000
Staff Name: Uma
ContractPeriod: 4years

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?

Dept of CSE, ATMECE, MYSURU Page 22


DAA LAB 18CSL47

/* 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 “/”. */

Objectives: This program enable students to :


 Learnhowtostoretheirnameanddate_of_birthinsideJavaclasscalledCustomer.

//input: name and dtae_of_birh in dd/mm/yyy format

//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();

System.out.println("enter date of birth in dd/mm/yyy format");

String date = sc.next();


4) A object is created of StringTokenizer class and is used for calling the method of this class.
5) The method “has more elements”and“nextElement” extracting the strings
separated by “/”delimeter
StringTokenizers tr Token = new StringTokenizer(date, "/");

while (strToken.hasMoreElements())

System.out.println(name +strToken.nextElement());

}
6) The output is displayed then in the form of<name, dd,mm,yyy>

Dept of CSE, ATMECE, MYSURU Page 23


DAA LAB 18CSL47

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();
}

public static void main(String[] args)


{
System.out.println("Enter the customer detail");
customer[] cus=new customer[30];
Scanner sc =new Scanner(System.in);

Dept of CSE, ATMECE, MYSURU Page 24


DAA LAB 18CSL47

System.out.println("enter the number of customer");


int n=sc.nextInt();

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:

Enter the customer detail


enter the number of
customer 2
Enter the customer name and date
monika
12/2/2017
gowda11/4/2017
monika,12,2,2017
gowda,11,4,2017

Dept of CSE, ATMECE, MYSURU Page 25


DAA LAB 18CSL47

Outcomes: On completion of this Program, the students are able to :

 Develop a program that can be solved to store the irname and date_of_birthinside
Java class called Customer

Viva questions:

1. Define string Tokenizer?


2. What is use of delimiter?
3. Define data types?
4. Define data members use in different data types?
5. How to create class in java?

Dept of CSE, ATMECE, MYSURU Page 26


DAA LAB 18CSL47

/* 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.*/

Objectives: This Program enable students to :

 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

b) Arithmetic exception raised and error message displayed when b = 0.


Steps :

1) A class is created containing the main method


2) Two variables are declared i.e. a andb
3) Input is obtained from console
Scanner sc = new Scanner(System.in);

a =sc.nextInt();
b =sc.nextInt();
4) To calculate division is kept under try block try{
System.out.println(a/b);

5) Arethemetic exception raised when b=0 handled in catchblock


tryblock
catch(Arithmetic Exception e){
e.printStackTrace();

Dept of CSE, ATMECE, MYSURU Page 27


DAA LAB 18CSL47

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:

Input two integers


6 2
Result=3
Input two integers
3 0
exception caught: Divide by zero error java.lang.ArithmeticException: / by zero

Dept of CSE, ATMECE, MYSURU Page 28


DAA LAB 18CSL47

Outcomes: On completion of this Program, the students are able to :

 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?

Dept of CSE, ATMECE, MYSURU Page 29


DAA LAB 18CSL47

/* 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();}}

Objectives: This Program enable students to :


 Learn Inheritance and Thread concepts injava

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.*;

class second implements Runnable


{
publicint x;
public second (int x)
{
this.x=x;
}
public void run()
{
System.out.println("Second thread:Square of the number is"+x*x);
}
}
class third implements Runnable
{
publicint x;
public third(int x)
{
this.x=x;

Dept of CSE, ATMECE, MYSURU Page 30


DAA LAB 18CSL47

public void run()


{
System.out.println("third thread:Cube of the number is"+x*x*x);
}
}
class first extends Thread
{
public void run()
{
intnum=0;
Random r=newRandom();
try
{

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());

}
}
}

public class multithread


{
Public static void main(String args[])
{
first a=new first();
a.start();
}

Dept of CSE, ATMECE, MYSURU Page 31


DAA LAB 18CSL47

OUTPUT:

first thread generated number is 65


Secondthread:Squareofthenumberis4225
third thread:Cube of the number is 274625
first thread generated number is33
Second thread:Square of the numberis1089
third thread:Cube of the number is 35937
first thread generated number is30
Second thread:Square of the number is 900
third thread:Cube of the number is 27000
first thread generated number is 29
Secondthread:Squareofthenumberis841
thirdthread:Cubeofthenumberis24389
first thread generated number is93
Second thread:Square of the number is 8649
third thread:Cube of the number is 804357

Dept of CSE, ATMECE, MYSURU Page 32


DAA LAB 18CSL47

Outcomes: On completion of this Program, the students are able to :


 Apply Inheritance and Thread concepts injava

Viva questions

1. What are threads?


2. What is inheritance?
3. How to implement multi-threads?
4. What is difference between process and threads?

Dept of CSE, ATMECE, MYSURU Page 33


DAA LAB 18CSL47

/*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.*/

Objectives: This Program enable students to :


• Learn Quick sorting and searchingtechniques.
• Get exposed to Quick Sort algorithm designtechniques.

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.

A[0]…A[s-1] A[s] A[s+1]…A[n-1]

Allare<=A[s] all are>=A[s]

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

• NOT stable sort

Dept of CSE, ATMECE, MYSURU Page 34


DAA LAB 18CSL47

• Significantly faster in practice, than otheralgorithms

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

s← partition ( A [l...r] ) //s in a split position


Quicksort(A[l...s-1])
Quicksort( A [s+1...r])

ALGORITHM

Partition ( A [l...r] )

// Partitions a subarray by using int first element as a pivot

// Input :A sub-array A [l...r] of A [0...n-1], defined by its left and right


Indices l and r (l<r)
// Output :A partition of A [l...r], with the split position returned as this
function’s value

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

swap ( A [i] , A [j] ) // undo the last swap when i > = j


swap ( A [l] , A [j] )
return j

Dept of CSE, ATMECE, MYSURU Page 35


DAA LAB 18CSL47

PROGRAM
import java.util.Random;
import java.util.Scanner;

public class quicksort{

static int max=2000;


int partition (int[] a, intlow,int high)
{
Int p,i,j,temp;
p=a[low];
i=low+1;
j=high;
while(low<high)
{
while(a[i]<=p&&i<high) i++;
while(a[j]>p)
void sort(int[] a,intlow,int high)
{

if(low<high)
{
int s=partition(a,low,high);
sort(a,low,s-1); sort(a,s+1,high);
}
}

public static void main(String[] args) {


// TODO Auto-generated method stub

int[ ] a;

int I,n; System.out.println("Enterthearraysize");


Scannersc=new Scanner(System.in);
n=sc.nextInt(); a= newint[max];
Random generator=new Random();

Dept of CSE, ATMECE, MYSURU Page 36


DAA LAB 18CSL47

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]);
}}

Dept of CSE, ATMECE, MYSURU Page 37


DAA LAB 18CSL47

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

Outcomes: On completion of this Program, the students are able to :

• Solve problems by applying Quick Sortalgorithms.

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

Dept of CSE, ATMECE, MYSURU Page 38


DAA LAB 18CSL47

/* 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)

Dept of CSE, ATMECE, MYSURU Page 39


DAA LAB 18CSL47

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;

whilei < p and j < q do


ifB[i] <= C[j]
A[k] ← B[i] ; i ← i + 1
elseA[k] ← C[j] ; j ← j + 1
k←k+1
ifi = p
copy C[j...q-1] to A[k...p+q-1]
else copy B[i...p-1] to A[k...p+q-q]

Time Complexity
C (n) € Θ (nlogn)

Mergesort is a perfect example of a successful application of the divide-and-conquer technique. The


steps followed in merge sort are:

 Mergesortworksbydividingthegivenarrayintotwosubarraysofequalsize

 The sub arrays are sorted independently usingrecursion

 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.

NOTE: IN MERGE SORT ELEMENTS ARE DIVIDED ACCORDING TO THEIR


POSITION.

Dept of CSE, ATMECE, MYSURU Page 40


DAA LAB 18CSL47

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]);
}}

Dept of CSE, ATMECE, MYSURU Page 42


DAA LAB 18CSL47

OUTPUT 1:
Enter Max array size: 6

The array elements are generated randomly:

-- -- -- -- -- --
Time Complexity (ms) for n = 6 is :0.307211

-------Sorted Array (Merge Sort)-----------------

120 123 240 342 730 968

BUILD SUCCESSFUL (total time: 12 seconds)

Outcomes: On completion of this Program, the students are able to :


• Solve problems by applying Merge Sortalgorithms

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

Dept of CSE, ATMECE, MYSURU Page 43


DAA LAB 18CSL47

6A). Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method

Objectives: This Program enable students to :

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:

// Initialization of first column and first row elements

Repeat for i = 0 to n

set V(i,0) = 0
Repeat for j = 0 toW
Set V(0,j) =0
//complete remaining entries

rowbyrowRepeat for i = 1 ton

repeat for j = 1 toW


if(wi<=j)V(i,j))=max{V(i-1,j),V(i-1,j-wi)+vi} if (

wi>j) V(i,j) =V(i-1,j)

PrintV(n,W)

Dept of CSE, ATMECE, MYSURU Page 44


DAA LAB 18CSL47

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];
}

Dept of CSE, ATMECE, MYSURU Page 45


DAA LAB 18CSL47
i--;
}
System.out.println("\nItems selected : ");
for ( i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(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);
}
}

Dept of CSE, ATMECE, MYSURU Page 46


DAA LAB 18CSL47

OUTPUT :

Knapsack Problem - Dynamic Programming


Solution: Enter the max capacity of knapsack:

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)

Outcomes: On completion of this Program, the students are able to :

 Solve0/1KnapsackproblemusingDynamicProgrammingmethodtoimplementinjava

Viva questions

1. What is dynamicprogram?
2. Knapsack problem can be solved by using whichmethod.
3. Whatisthedifferencebetweendynamicmethodandgreedymethodprograming
Techniques ?

Dept of CSE, ATMECE, MYSURU Page 47


DAA LAB 18CSL47

/*6B. Implement in Java, the 0/1 Knapsack problem using Greedy method.*/

Objectives: This Program enable students to :

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.

//Output: The value of an optimal feasible subset of the first i items.

//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

if j< Weights[i] then


value = Knapsack ( i-1, j )

else
value = max ( Knapsack ( i -1, j ),
values[I] + Knapsack ( i-1, j-Weights[i] ) )
V[i j] = value

return V [ i, j ]

Dept of CSE, ATMECE, MYSURU Page 48


DAA LAB 18CSL47

Efficiency:

• Running time of Knapsack problem using dynamic programming algorithm is:

• O( n * W)

• Time needed to find the composition of an optimal solution is: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 the capacity is zero, profit is also zero.

When the weight is zero , profit is also zero.

When knapsack capacity is less than weight then profit is the previous profit

When all above cases fails then the formula to be applied is

Profit = Max (profit by previous object for capacity j,

profit by current object+ profit by previous object for current weight difference)

where weight difference=capacity-weight.

Dept of CSE, ATMECE, MYSURU Page 49


DAA LAB 18CSL47

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)
{

Dept of CSE, ATMECE, MYSURU


Page 50
DAA LAB 18CSL47
System.out.println("Quantity of item number: "+ (j+1) + " added is " +m);
sum+=m*max;
m=-1;
}
else
{
System.out.println("Quantity of item number: " + (j+1) + " added is " + array[0][j]);
m-=array[0][j];
sum+=(float)array[1][j];
array[1][j]=0;
}
System.out.println("The total profit is " + sum);
sc.close();
}
}

Dept of CSE, ATMECE, MYSURU


Page 51
DAA LAB 18CSL47

OUTPUT:

Enter number of items:


4
Enter maximum volume of knapsack:
5
Enter the weights of each items:
3
1
2
4
Enter the values of each items:
5
4
3
2
i=2
The Solution
vector, x[ ]: 1.0
1.0 0.5 0.0
Total profit is = 10.5

BUILD SUCCESSFUL (total time: 10 minutes 5 seconds)

Outcomes: On completion of this Program, the students are able to :

 Solve 0/1 Knapsack problem using Greedy method to implement injava

Viva questions :

1. What is dynamicprogram?
2. Knapsack problem can be solved by using whichmethod.
3. Whatisthedifferencebetweendynamicmethodandgreedymethodprograming
Techniques?

Dept of CSE, ATMECE, MYSURU Page 52


DAA LAB 18CSL47

* 7.Fromagivenvertexinaweightedconnectedgraph,findshortestpathstoothervertices using
Dijkstra's algorithm. Write the program inJava.*/

Objectives: This Program enable students to :


 LearnDijkstra'ssortingandsearchingtechniquestofindshortestpaths. Get
exposed to Dijkstra's algorithm designtechnique

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

Sv: starting vertex. Dv: destination vertex.

Dept of CSE, ATMECE, MYSURU Page 53


DAA LAB 18CSL47

Aim:
Algorithm:
// Input: A weighted connected graph G ={V,E}, source s

// Output dv: the distance-vertex matrix


• Read number of vertices of graphG

• Read weighted graphG

• 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

• Repeat for y = 1 ton

v = next vertex with minimum dv value, by calling FindNextNear()


Add v to tree.

For all the adjacent u of v and u is not added to the tree,


if dv[u]> dv[v]+wt_graph[v,u] then
dv[u]=dv[v]+wt_graph[v,u]andprev[u]=v.
findNextNear

//Input: graph, dv matrix

//Output: j the next nearest vertex

ominm = 9999 o For k =1 to n


ifkvertexisnotselectedintree
and if dv[k] <minm

{ minm = dv [k]
j=k

Dept of CSE, ATMECE, MYSURU Page 54


DAA LAB 18CSL47

PROGRAM
Import java.util.Scanner;
public class Dijkstra {
int d[ ]=new int[10];
int p[ ]=new int[10];
int visited[ ]=new int[10];

public void dijk(int[][]a, int s, int n)


{
int u=-1,v,i,j,min;
for(v=0;v<n;v++)
{
d[v]=99;
p[v]=-1;
}
d[s]=0;
for(i=0;i<n;i++){
min=99;
for(j=0;j<n;j++){
if(d[j]<min&& visited[j]==0)
{
min=d[j]; u=j;
}
}
visited[u]=1;
for(v=0;v<n;v++){
if((d[u]+a[u][v]<d[v])&&(u!=v)&&visited[v]==0)
{
d[v]=d[u]+a[u][v]; p[v]=u;
}
}
}

Dept of CSE, ATMECE, MYSURU Page 55


DAA LAB 18CSL47

}
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) {

int a[][]=new int[10][10];

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++)

Dept of CSE, ATMECE, MYSURU Page 56


DAA LAB 18CSL47

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:

enter the number of vertices 5


enter the weighted matrix
0 3 99 7 99
3 0 4 299
99 4 0 56
52504
99 99 6 4 0
enter the source vertex 0
the shortest path between source0to remaining vertices are

0 ->1 =3
0 ->1 ->2=7
0 ->1 ->3=5
0 ->1 ->3 ->4 =9

Dept of CSE, ATMECE, MYSURU Page 57


DAA LAB 18CSL47

Outcomes:On completion of this Program, the students are able to :


 Solve Dijkstra's sorting and searching techniques to find shortestpaths.
 Develop a program that can be solved to Dijkstra's algorithm designtechniques.

Viva questions

1. How do you represent thegraph?

2. Application of DijkstrasAlgorithm.

3. Difference between Floyds and Dijkstrasalgorithm.

4. Dijkstras algorithm can b esolved by using which type algorithm method.

Dept of CSE, ATMECE, MYSURU Page 58


DAA LAB 18CSL47

/* 8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm. Implement the program in Java language. */

Objectives:This Program enable students to :

 Learn Kruskal's algorithm to find shortestpaths.


 FindMinimumCostSpanningTreeofagivenundirectedgraphusingKruskal's
algorithm

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.

DCBA

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.

Dept of CSE, ATMECE, MYSURU Page 59


DAA LAB 18CSL47

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.

• Initially, each vertex is in its own tree inforest.

• Then, algorithm consider each edge in turn, order by increasing weight.

• edge(u,v) connects two different trees,then(u,v) is added tothesetofedgesof


theMST,and two trees connected by an edge(u,v) aremergedintoasingletree.

• Ontheotherhand,ifanedge(u,v)connectstwoverticesinthesametree,thenedge(u,
v) is discarded.

Dept of CSE, ATMECE, MYSURU Page 60


DAA LAB 18CSL47

PROGRAM
import java.util.Scanner;

public class kruskal {

int parent[]=new int[10];


int find(int m)
{
int p=m;
while(parent[p]!=0)
p=parent[p];
return p;
}

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)
{

Dept of CSE, ATMECE, MYSURU Page61


DAA LAB 18CSL47

union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]);

sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=99;
}

System.out.println("The cost of minimum spanning tree = "+sum);

public static void main(String[] args) {


int a[ ][ ]=new int[10][10];
inti,j;
System.out.println("Enter the number of vertices of the graph");
Scanner sc=new Scanner(System.in);
int n; n=sc.nextInt();
System.out.println("Enter the wieghted matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt(); kruskal k=new
kruskal(); k.krkl(a,n);
sc.close();

}
}
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

Dept of CSE, ATMECE, MYSURU Page 62


DAA LAB 18CSL47

Outcomes: On completion of this Program, the students are able to :


 Solve Kruskal's algorithm to find shortestpaths.
 SolveMinimumCostSpanningTreeofagivenundirectedgraphusingKruskal's
algorithm

Viva questions

1 Which are the data structures is used to represent thegraph.


2 What is tree?
3 What is spanningtree?
4 What is MST (Minimum-cost SpanningTree)?
5 DifferencebetweenGreedyalgorithmandDynamicalgorithmmethod.

Dept of CSE, ATMECE, MYSURU Page 63


DAA LAB 18CSL47

9 .FindMinimumCostSpanningTreeofagivenundirectedgraphusingPrim'salgorithm.
Implement the program in Javalanguage.

Objectives: This Program enable students to :

 Learn Prim's algorithm to find shortestpaths.


 Find Minimum Cost Spanning Tree of a given undirected graphusing Prim'salgorithm
Choose a node and build a tree from there selecting at every stage the shortest available edge that
can extend the tree to an additional node.

• Prim'salgorithmhasthepropertythattheedgesinthesetAalwaysformasingletree.
• Webegin with vertexvinagivengraph G=(V,E),defining the initial set of
vertices A.

• In each iteration,we choose a minimum-weightedge(u,v),connecting a vertex v in the


set A to the vertex u outside of set A.

• ThevertexuisbroughtintoA.Thisprocessisrepeateduntilaspanningtreeisformed.

Dept of CSE, ATMECE, MYSURU Page 64


DAA LAB 18CSL47

PROGRAM

public class prims {


public static void main(String[] args) {
int w[ ][ ]=new int[10][10]; int
n,i,j,s,k=0;
int min;
int sum=0; int
u=0,v=0; int
flag=0;
int sol[ ]=new int[10];
System.out.println("Enter the number of vertices");
Scanner sc=new Scanner(System.in); n=sc.nextInt();
for(i=1;i<=n;i++)
sol[i]=0;
System.out.println("Enter the weighted graph");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=sc.nextInt();
System.out.println("Enter the source vertex");
s=sc.nextInt();
sol[s]=1;
k=1;
while (k<=n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sol[i]==1&&sol[j]==0)
if(i!=j&&min>w[i][j])
{
min=w[i][j];
u=i;
v=j;
}
sol[v]=1;

Dept of CSE,ATMECE,MYSURU Page65


DAA LAB 18CSL47

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

Dept of CSE, ATMECE, MYSURU Page 66


DAA LAB 18CSL47

Outcomes: On completion of this Program, the students are able to :

 Solve Prim’s algorithm to find shortest paths.


 SolveMinimumCostSpanningTreeofagivenundirectedgraphusingPrim’salgorithm

Viva questions

 What is the difference between Prims and Kruskalsalgorithm?


 Can we use kruskals to find maximum cost spanningtree.
 What is minimum cost spanningtree.

Dept of CSE, ATMECE, MYSURU Page 67


DAA LAB 18CSL47

/*10A. Write Java programs to implement All-Pairs Shortest Paths problem using
Floyd's algorithm.*/

Objectives: This Program enable students to :

 Learn Floyd’s algorithm to findAll-Pairs Shortestpaths.


 FindMinimumCostSpanningTreeofagivenundirectedgraphusingFloyd’salgorithm

Floyds algorithm is a classic example for the application ofdynamicprogramming.Itisusedto


compute the shortest distance between every two pair of nodes ina given graph and hence it is
also called “all-pair shortest path”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

// Input: Weight matrix W

// Output: Distance matrix of shortest paths’ length

D(0)w
fork1 to n do
fori1 to n do
forj1 to n do
D(k)min{d(k-1)[i,j], d(k-1)[i,k]+d(k-1)[k,j]}
ReturnD(n)

Dept of CSE, ATMECE, MYSURU Page 68


DAA LAB 18CSL47

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]);
}

public static void main(String[] args) {


int a[ ][ ]=new int[10][10];
intn,i,j;
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=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
floyd f=new floyd();
f.flyd(a, n);
System.out.println("Theshortestpathmatrixis");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
sc.close();

Dept of CSE, ATMECE, MYSURU Page 69


DAA LAB 18CSL47

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:

 Solve Floyd’salgorithm to findAll-Pairs Shortest paths.


 Solve &Find Minimum Cost Spanning Tree ofa given undirected graph using Floyd’s
algorithm

Viva questions

 Floyd’s algorithm is an example of which typeofalgorithm.


 Difference between Floyds and Dijkstra’salgorithm.
 What is the time complexity of Floyd’salgorithm?
 What is the best,worst and average case of Floyd’salgorithm?

Dept of CSE, ATMECE, MYSURU Page 70


DAA LAB 18CSL47

10 B.WriteJavaprogramstoimplementTravellingSalesPersonproblemusingDynamic
programming.*/
Objectives: This Program enable students to :

 Learn Travelling Sales Person problem.


 Find Minimum Traveling Distance using Dynamicprogramming

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.

Dept of CSE, ATMECE, MYSURU Page 71


DAA LAB 18CSL47

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;

Dept of CSE, ATMECE, MYSURU


Page 73
DAA LAB 18CSL47
min index=input Set[i];
}
}
return min index;
}
public void eval()
{
int dummy Set[]=new int[n-1];
for(int i=1;i<n;i++)
dummy Set[i-1]=i;
finalCost=COST(0,dummySet,n-1);
construct Tour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2]; for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}

Dept of CSE, ATMECE, MYSURU


Page 74
DAA LAB 18CSL47
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSP
{
public static void main(String args[])
{
TSPExp obj=new TSPExp();
}
}

Dept of CSE, ATMECE, MYSURU


Page 75
DAA LAB 18CSL47

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

BUILD SUCCESSFUL (total time: 21 seconds)

Program Outcomes: On Completion of these Program :

 Study Travelling Sales Person problem.


 Study Minimum Traveling Distance using Dynamicprogramming

Viva questions

 Application of travelling salesmenproblem.


 What is the time complexity ofTSP?
 How TSP is different from Dijkstras, Prims and Kruskalsalgorithm

Dept of CSE, ATMECE, MYSURU Page 74


DAA LAB 18CSL47

11. DesignandimplementinJavatofindasubsetofagivensetS={Sl,S2,.................... ,Sn} ofn


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.*/

Objectives:This Program enable students to :

 Learn Subset problem.


 Find SUM is equal to a given positive integer

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.

This problem is NP-complete.


This problem arises in practical applications. Similar to the knapsack problem we may have a
truck that can carry at most t pounds and we have n different boxes to ship and the ith box
weighs xi pounds. The naive approach of computing the sum of the elements of every subset of
S and then selecting the best requires exponential time. Below we present an exponential time
exact algorithm.

• Algorithm:
• accept n: no of items inset

• accept their values, sk in increasingorder


• accept d: sum of subsetdesired

• initialize x[i] = -1 for alli

• check if solution possible ornot

• if possible then call SumOfSub(0,1,sum ofallelements)


• SumOfSub (s, k,r)
//Values of x[ j ], 1 <= j < k, have been determined
//Node creation at level k taking place: also call for creation at level K+1 if possible
// s = sum of 1 to k-1 elements and r is sum of k to n elements

Dept of CSE, ATMECE, MYSURU Page 75


DAA LAB 18CSL47

//generating left child that means including k in solution


• Set x[k] =1
• If (s + s[k] = d) then subset found, printsolution

• 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;

SumOfSub(s, k+1, r – s[k])

Dept of CSE, ATMECE, MYSURU Page 76


DAA LAB 18CSL47

PROGRAM

importjava.util.Scanner;
import static java.lang.Math.pow;

public class subSet {

void subset(intnum,int n, int x[])


{
int i; for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}

public static void main(String[] args) {


// TODO Auto-generated method stub
inta[]=new int[10];
int x[]=new int[10];
intn,d,sum,present=0; int j;
System.out.println("enter the number of elements of set"); Scanner
sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("enter the elements of set"); for(int
i=1;i<=n;i++)
a[i]=sc.nextInt();
System.out.println("enter the positive integer sum");
d=sc.nextInt();
if(d>0)
{
for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subSet s=new subSet();
s.subset(i,n,x);
sum=0; for(j=1;j<=n;j++)
if(x[j]==1)sum=sum+a[j];

if(d==sum)
{
System.out.print("Subset={");
present=1;
for(j=1;j<=n;j++)

Dept of CSE, ATMECE, MYSURU Page 77


DAA LAB 18CSL47

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:

enter the number of elements of set 5


enter the elements of set 1 2 5 6 8
enter the positive integer sum 9
Subset={1,8,}=9
Subset={1,2,6,}=9

Outcomes :This Program enable students to :

 Study Subset problem.


 Study SUM is equal to a given positiveinteger

Viva questions

 Solve the given problem for subset sum int[] A = { 3, 2, 7, 1}, S =6


 Give the time complexity equation for subsetsum.
 Subset problem can be solved by using which type ofalgorithm.
 What is the difference between Backtracking and Branch and boundalgorithm?

Dept of CSE, ATMECE, MYSURU Page 78


DAA LAB 18CSL47

12. DesignandimplementthepresenceofHamiltonianCycleinanundirectedGraphG of
nvertices.*/
objectives: This Program enable students to :

To find Hamiltonian Cycle in an undirected Graph G of n vertices.


Algorithm:
Input:
A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is
adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge
from i to j, otherwise graph[i][j] is 0.

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.

Dept of CSE, ATMECE, MYSURU Page 79


DAA LAB 18CSL47

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();
}

public void nextValue (int k)


{
int i=0;
while(true)
{
x[k]=x[k]+1;
if (x[k]==n)
x[k]=-1;
if (x[k]==-1)
return;
if (adj[x[k-1]][x[k]]==1)
for (i=0; i<k; i++)
if (x[i]==x[k])
break;
if (i==k)
if (k<n-1 || k==n-1 &&adj[x[n-1]][0]==1)
return;
}
}

Dept of CSE, ATMECE, MYSURU Page 80


DAA LAB 18CSL47

public void getHCycle(int k)


{
while(true)
{
nextValue(k);
if (x[k]==-1)
return; if (k==n-1)
{
System.out.println("\nSolution : ");
for (int i=0; i<n; i++)
System.out.print((x[i]+1)+" ");
System.out.println(1);
}
elsegetHCycle(k+1);
}
}

}
classHamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycleobj=new Hamiltoniancycle();
obj.getHCycle(1);
}
}

Dept of CSE, ATMECE, MYSURU Page 81


DAA LAB 18CSL47

Output:

Enter the number of nodes 6


Enter the adjacency matrix
011 1 0 0
101 0 0 1
110 1 1 0
101 0 1 0
001 1 0 1
010 0 1 0

Solution:
1265341
Solution:
1265431
Solution:
1326541
Solution:
1345621
Solution:
1435621
Solution:
1456231

Outcomes: On Completion of these Program enable students to : Solve

Hamiltonian Cycle in an undirected Graph G of n vertices.

Viva questions

 What is N-Queensproblem?
 Difference between ‘Branch and bound’ and ‘Backtracking’algorithm.
 What is the time complexity of N-queensproble

Dept of CSE, ATMECE, MYSURU Page 82

You might also like