Академический Документы
Профессиональный Документы
Культура Документы
LABORATORY MANUAL
DESIGN AND ANALYSIS OF ALGORITHMS
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2015 -2016)
15CSL47
PREPARED BY
Mission
To achieve academic excellence in science, engineering and technology through
dedication to duty, innovation in teaching and faith in human values.
To enable our students to develop into outstanding professional with high ethical
standards to face the challenges of 21st century.
To provide educational opportunities to the deprived and weaker section of the
society to uplift their socio-economic status.
Vision
To empower students through wholesome education and enable the students to
develop into highly qualified and trained professionals with ethics and emerge as
responsible citizen with broad outlook to build a vibrant nation.
Mission
To provide excellent technical knowledge and computing skills to make the
graduates globally competitive with professional ethics.
To involve in research activities and be committed to lifelong learning to make
positive contributions to the society.
Vision
To advance the intellectual capacity of the nation and the international
community by imparting knowledge to graduates who are globally recognized as
innovators, entrepreneur and competent professionals.
15CSL47 Design and Analysis of Algorithms Lab Manual
Programme Outcomes
a. Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex
engineering problems.
b. Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences
c. Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs with
appropriate consideration for public health and safety, cultural, societal and
environmental considerations.
d. Conduct investigations of complex problems using research-based knowledge and
research methods including design of experiments, analysis and interpretation of data
and synthesis of information to provide valid conclusions.
e. 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 under- standing of the limitations.
f. The Engineer and Society: Apply reasoning informed by contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to professional engineering practice.
g. Environment and Sustainability: Understand the impact of professional
engineering solutions in societal and environmental contexts and demonstrate
knowledge of and need for sustainable development.
h. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of engineering practice.
i. Individual and Team Work: Function effectively as an individual, and as a
member or leader in diverse teams and in multi disciplinary settings.
Course objectives:
This course 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
List of Experiments
Sl Experiment Page
No. No.
1. Write a Java program to print the sum of two numbers. 8
2. Write a program in Java to print the first 5 fibonocci numbers 9
3. Write a Java program that reads a number as command line argument 10
and prints its multiplication table upto 10.
4. Write a program in Java to implement Bubble Sort. 12
5. Write a program in Java to find sum of elements in an array. 14
9. Sort a given set of n integer elements using Merge Sort method and 23
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.
10. From a given vertex in a weighted connected graph, find shortest 26
paths to other vertices using Dijkstra's algorithm. Write the program
in Java.
Course Outcomes:
After studying this course, students will be able to
CO1. Design algorithms using appropriate design techniques (brute-force, greedy,
dynamic programming, etc.)
CO2. Implement a variety of algorithms such assorting, graph related, combinatorial, etc.,
in a high level language.
CO3. Analyze and compare the performance of algorithms using language features.
CO4. Apply and implement learned algorithm design techniques and data structures to
solve real world problems.
PO a b c d e f g H I j k l m n o
CO
1 3 3 3 3 3 - - - - - - - 3 3 -
2 3 3 3 3 3 - - - - - - - 3 3 -
3 3 3 3 3 3 - - - - - - - 3 3 -
4 3 3 3 3 3 - - - - - - - 3 3 -
3 - High correlation
2 - Moderate (Medium) correlation
1 - Slight (Low) correlation
- - No contribution
Program 1
Sum of Two Numbers
Algorithm
Algorithm sum
{
Read a & b.
Write c:=a+b.
}
Program
import java.io.*;
import java.util.Scanner;
public class sum
{
public static void main(String[] args)
{
System.out.println("enter two integers a and b");
Scanner in = new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int c;
c=a+b;
System.out.println("the sum of a+b is:"+c);
}
}
Output
O1: enter two integers a and b 5 6 O2: enter two integers a and b 10 20
the sum of a+b is:11 the sum of a+b is:30
Program 2
Fibonacci Numbers
Algorithm
Algorithm fibo
{
f:=0,s:=1
for i:= 1 to 3 do
fib:=f+s, f:=s,s:=fib.
Write fib
}
Program
public class fibo {
public static void main(String[] args) {
int f=0,s=1;
System.out.println(" The first 5 fibonocci numbers are");
System.out.println(f);
System.out.println(s);
for(int i=1;i<=3;i++)
{
int fib=f+s;
System.out.println(fib);
f=s;
s=fib;
}
}
}
Output
The first 5 fibonocci numbers are
0
1
1
2
3
Program 3
Multiplication Table
3) Write a Java program that reads a number as command line argument and prints its
multiplication table upto 10.
Algorithm
Algorithm multitab
{
Read n
For c:=1to 10 do
Write multiplication table of n upto 10
}
Program
public class multitab {
public static void main(String[] args)
{
int n,c;
n=Integer.parseInt(args[0]);
System.out.println("multiplication table of"+n+"is :-");
for (c=1;c<=10;c++)
System.out.println(n+" *"+c+" ="+(n*c));
}
}
Output
O1: O2:
multiplication table of10is :- multiplication table of5is :-
10 *1 =10 5 *1 =5
10 *2 =20 5 *2 =10
10 *3 =30 5 *3 =15
10 *4 =40 5 *4 =20
10 *5 =50 5 *5 =25
10 *6 =60 5 *6 =30
10 *7 =70 5 *7 =35
10 *8 =80 5 *8 =40
10 *9 =90 5 *9 =45
10 *10 =100 5 *10 =50
O3: O4:
multiplication table of15is :- multiplication table of20is :-
15 *1 =15 20 *1 =20
15 *2 =30 20 *2 =40
15 *3 =45 20 *3 =60
15 *4 =60 20 *4 =80
15 *5 =75 20 *5 =100
15 *6 =90 20 *6 =120
15 *7 =105 20 *7 =140
15 *8 =120 20 *8 =160
15 *9 =135 20 *9 =180
15 *10 =150 20 *10 =200
O5:
multiplication table of25is :-
25 *1 =25
25 *2 =50
25 *3 =75
25 *4 =100
25 *5 =125
25 *6 =150
25 *7 =175
25 *8 =200
25 *9 =225
25 *10 =250
Program 4
Bubble Sort
Algorithm
Algorithm BubbleSort
{
Read the limit n
Accept the array elements
for i:=0 to n-1 do 5 to 6
for j:=0 to (n-i-1) do step 6
swap a[j] and a[j+1]
Write the sorted list
}
Program
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
Output
O1: O2:
Input number of integers to sort 5 Input number of integers to sort 4
Enter 5 integers 5 4 3 2 1 Enter 4 integers
Sorted list of numbers Sorted list of numbers
1 12
2 13
3 34
4 62
5
O3: O4:
Input number of integers to sort 7 Input number of integers to sort
Enter 7 integers 1 2 3 4 5 6 7 Enter 3 integers
Sorted list of numbers Sorted list of numbers
1 0
2 100
3 345
4
5
6
7
O5:
Input number of integers to sort 6
Enter 6 integers
Sorted list of numbers
-23
-1
7
8
10
56
Program 5
Sum of Array Elements
Algorithm
Algorithm sumOfElements
{
Read the number pf elements
Read the array
for i:=0 to n do
sum:=sum+a[i]
Write sum
}
Program
import java.util.Scanner;
class sumOfElements {
public static void main(String []args) {
int n,i,j,sum=0;
Scanner in = new Scanner(System.in);
Output
O1: Input the number of elements in the array 5 O2: Input the number of elements in the array 4
Enter 5 integers 1 2 3 4 5 Enter 4 integers -1 4 5 0
The sum of elements15 The sum of elements8
O3: Input the number of elements in the array 6 O4: Input the number of elements in the array 2
Enter 4 integers 8 -3 4 5 8 0 Enter 4 integers -1 4
The sum of elements 22 The sum of elements3
O5: Input the number of elements in the array 3
Enter 4 integers 5 4 3
The sum of elements12
Program 6
Reverse a String
6) Write a program in Java to reverses the contents of a string given on console and
display the original string and the reversed string.
Algorithm
Algorithm strcon
{
Read string to reverse.
Write the original string
For i:=str1.lenght()until i>0
Res:=res+str1.charat(i)
Write reversed string
}
Program
import java.util.Scanner;
public class strcon {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String str1,res;
System.out.print("enter the string to be reversed :\n");
str1=input.next();
System.out.print("the original string is:\n"+str1);
res="";
System.out.print("\n the reversed string is:\n");
for(int i=str1.length()-1;i>=0;i--)
res=res+str1.charAt(i);
System.out.println(res);
}
}
Output
O1: enter the string to be reversed :Hello O2: enter the string to be reversed :java
the original string is: the original string is:
Hello java
the reversed string is: the reversed string is:
olleH avaj
O3: enter the string to be reversed :Madam O4: enter the string to be reversed :Algorithms
the original string is: the original string is:
Madam Algorithms
the reversed string is: the reversed string is:
madam smhtiroglA
Program 7
Uppercase Function
7) Write a program in Java to read a string given on console and change the case of the
string and display the original string and the resultant string.
Algorithm:
Algorithm strcase
{
Read string to change the case.
Write the original string
Write res:=str1 to Uppercase
Write resultant string
}
Program:
import java.util.Scanner;
public class strcase {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String str1,res;
System.out.print("enter the string :\n");
str1=input.next();
System.out.print("the original string is:\n"+str1);
System.out.print("\n the resultant string is:\n");
res=str1.toUpperCase();
System.out.println(res);
}
}
Output:
O1: enter the string : hello O2: enter the string : object
the original string is: the original string is:
hello object
the resultant string is: the resultant string is:
HELLO OBJECT
O3:enter the string :java O4: enter the string :c++
the original string is: the original string is:
java c++
the resultant string is: the resultant string is:
JAVA C++
Program 8
Class Programs
8) a.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
Algorithm:
Algorithm staffdetail
{
Write choice
1. Teaching, 2. Technical 3. Contract, 4. Exit
Read choice
Case choice
Case 1: Read name , staff_id, Phone number, Salary, Domain, no of publication
Write name , staff_id, Phone number, Salary, Domain, no of publication
Case 2: Read name , staff_id, Phone number, Salary, skills
Write name , staff_id, Phone number, Salary, skills
Case 3: Read name , staff_id, Phone number, Salary, period
Write name , staff_id, Phone number, Salary, period
}
Program:
import java.util.Scanner;
abstract class staff
{
String name;
int staffid;
String phno;
double salary;
staff(String n,int id,String p,double sal)
{
name=n;
staffid=id;
phno=p;
salary=sal;
}
abstract void display();
};
no_of_publication=nop;
}
void display()
{
System.out.println("Teaching staff details:");
System.out.println("name \t staffid phno \tsalary \tdomain \t no_of_publication");
System.out.println(name+" \t "+staffid+" \t "+ phno+"\t"+salary+"\t"+domain+"
\t"+no_of_publication);
}
};
class technical extends staff
{
String skills;
technical(String name ,int id,String p,double sal,String skl )
{
super(name,id,p,sal);
skills=skl;
}
void display()
{
System.out.println("Technical staff details:");
System.out.println("name \t staffid\tphno\tsalary\tskills");
System.out.println(name+" \t"+staffid+" \t"+phno+" \t"+salary+"\t"+skills);
}
};
class contract extends staff
{
int period;
contract(String n,int id,String p,double sal,int prd)
{
super(n,id,p,sal);
period=prd;
}
void display()
{
System.out.println("contract staff details:");
System.out.println("name \t staffed \t phno \t salary \t period");
System.out.println(name+" \t"+staffid+" \t"+phno+" \t"+salary+"\t"+period);
}
};
class staffdetail
{
public static void main(String args[])
{
staff s;
while(true)
{
Scanner in = new Scanner(System.in);
System.out.println("1.teaching staff\n 2.technical\n3.contract\n4.exit");
System.out.println("enter your choice:");
int c=in.nextInt();
switch(c)
{
case 1: System.out.println("enter teaching staff details:");
System.out.println("enter name \t staffid\tphno\tsalary\tdomain\tno_of_publication");
String n=in.next();
int sfid=in.nextInt();
String pn=in.next();
double sal=in.nextDouble();
String dom=in.next();
int n_o_pub=in.nextInt();
teaching tc=new teaching(n,sfid,pn,sal,dom,n_o_pub);
s=tc;
s.display();
break;
case 2:
System.out.println("enter technical staff details:");
System.out.println("enter name \t staffid\tphno\tsalary\tskills");
n=in.next();
int sid=in.nextInt();
pn=in.next();
sal=in.nextDouble();
String skills=in.next();
technical t=new technical(n,sid,pn,sal,skills);
s=t;
s.display();
break;
case 3:
System.out.println("enter contract staff details:");
System.out.println("enter name \t staffid\tphno\tsalary\tperiod");
n=in.next();
sid=in.nextInt();
String pno=in.next();
sal=in.nextDouble();
int period=in.nextInt();
contract cr=new contract(n,sid,pno,sal,period);
s=cr;
s.display();
break;
default: System.exit(0);
}
}
}
}
Output:
1.teaching staff
2.technical
3.contract
4.exit
4.exit
enter your choice:4
8 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 “/”.
Algorithm:
Algorithm customer
{
Read customer name and DOB
Write Customer name
Write Dob as DD,mm.yyyy
}
Program:
import java.util.StringTokenizer;
import java.util.Scanner;
class customer
{
String name;
String dob;
void readdata()
{
System.out.println("enter the customer details: name and date_of_birth delimited
by/");
Scanner in = new Scanner(System.in);
name=in.next();
dob=in.next();
}
void display()
{
StringTokenizer st = new StringTokenizer(dob,"/");
System.out.println(" the customer data is:");
System.out.print("<"+name);
while (st.hasMoreTokens())
System.out.print(","+st.nextToken());
System.out.println(">");
}
public static void main(String args[])
{
customer c= new customer();
c.readdata();
c.display();
}
}
Output:
O1: enter the customer details: name and O2: enter the customer details: name and
date_of_birth delimited by/Kripa 25/06/1992 date_of_birth delimited by/Divya 02/05/1989
the customer data is: the customer data is:
<Kripa,25,06,1992> <Divya,02,06,1992>
O3: enter the customer details: name and O4: enter the customer details: name and
date_of_birth delimited by/Lekshmy 27/04/1988 date_of_birth delimited by/Daksh 20/10/2017
the customer data is: the customer data is:
<Lekshmy,27,04,1988> <Daksh,20,10,2017>
O5: enter the customer details: name and
date_of_birth delimited by/Sree 29/02/1965
the customer data is:
<Sree,29,02,1965>
Program 9
Merge Sort
9) 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.
Algorithm:
Program:
import java.util.Scanner;
class msort
{
long a[];
void merge(long a[],int low,int mid,int high)
{
int i,j,k;
long b[]= new long[10000];
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]<a[j])
{
b[k]=a[i];
k=k+1;
i=i+1;
}
else
{
b[k]=a[j];
k=k+1;
j=j+1;
}
}
while(i<=mid)
{
b[k]=a[i];
k=k+1;
i=i+1;
}
while(j<=high)
{
b[k]=a[j]; k=k+1; j=j+1;
}
for(i=low;i<=k-1;i++)
a[i]=b[i];
}
void mergesort(long a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
public static void main(String args[])
{
msort sorter=new msort();
System.out.println("\n Enter the number of elements : ");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
long [] input = new long [n];
for(int i=0;i<n;i++)
{
input[i]= (long) Math.round(Math.random() * 5000);
}
long startime=System.currentTimeMillis();
sorter.mergesort(input,0,n-1);
long endtime= System.currentTimeMillis();
long totaltime= endtime-startime;
for(int j=0;j<n;j++)
System.out.println(input[j]);
System.out.println("Total time required for execution=" + totaltime +"ms");;
System.out.println("the best case and average case and worst time complexity= "
+n*Math.log(n));
}
}
Output:
O1:Enter the number of elements: 4000 O2: Enter the number of elements: 10000
Total time required for execution=90ms Total time required for execution=208ms
the best case and average case and worst time the best case and average case and worst time
complexity= 33176.19856040811 complexity= 92103.4037197618
O3:Enter the number of elements: 400 O4:Enter the number of elements: 40
Total time required for execution=8ms Total time required for execution=0ms
the best case and average case and worst time the best case and average case and worst time
complexity= 2396.5858188431926 complexity= 147.55517816455745
O5:Enter the number of elements: 4
Total time required for execution=0ms
the best case and average case and worst time
complexity= 5.545177444479562
Program 10
Dijkstra’s Algorithm
10) From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm. Write the program in Java.
Algorithm:
//G be a graph
//Cost matrix [1:n,1:n] for the graph G
//S={set of vertices that path already generated}
//Let V be source vertex
//dist[j];1<=j<=n denotes distance between V and j
main()
{
for i:=1 to n do
{
s[i]=false; // initialize s with n
dist[i]=cost[v,i]; //define distance
}
s[v]=true; //put v in s
dist[v]=0.0; //Distance between v and v is 0
for num:=2 to n-1 do
{
paths from v //choose u from among those vertices not in S such that dist[u]=min;
s[u]=true;
for(each w adjascent to u with s[w]=false)
if(dist[w]>dist[u]+cost[u,w])
then
dist[w]=dist[u]+cost[u,w]; //update the distance
}
}
Program:
import java.util.Scanner;
public class dijk {
int cost[][] = new int[10][10];
int dist[]= new int[100];
void dij(int n,int v)
{
int i,u,count,w,min;
u=0;
int flag[]= new int[10];
for(i=1;i<=n;i++)
{
flag[i]=0;
dist[i]=cost[v][i];
}
count=2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && flag[w]==0)
{
min=dist[w];
u=w;
flag[u]=1;
}
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && flag[w]==0)
dist[w]=dist[u]+cost[u][w];
}
}
public static void main(String args[])
{
int n,v,i,j;
dijk g= new dijk();
Scanner in= new Scanner(System.in);
System.out.println(" Enter the number of nodes:");
n= in.nextInt();
System.out.println(" Enter the cost matrix:");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
g.cost[i][j]=in.nextInt();
if(g.cost[i][j]==0)
g.cost[i][j]=999;
}
System.out.println(" Enter the source matrix:");
v=in.nextInt();
g.dij(n,v);
System.out.println(" Shortest path:");
for(i=1;i<=n;i++)
if(i!=v)
System.out.println(v + "->" + i + "\t" + "cost="+ g.dist[i]+ "\n");
}
}
Output:
O2:
O1: Enter the number of nodes:6
Enter the number of nodes:5 Enter the cost matrix:
Enter the cost matrix: 999 7 9 999 999 14
999 3 999 7 999 7 999 10 15 999 999
3 999 4 2 999 9 10 999 11 999 2
7 2 5 999 4 999 15 11 999 6 999
999 999 1 4 999 999 999 999 6 999 9
Enter the source matrix:1 14 999 2 999 9 999
Shortest path: Enter the source matrix:1
1->2 cost=3 Shortest path:
1->3 cost=7 1->2 cost=7
1->4 cost=5 1->3 cost=9
1->5 cost=8 1->4 cost=20
1->5 cost=20
1->6 cost=11
O3: O4:(negative edge)
Enter the number of nodes:5 Enter the number of nodes:3
Enter the cost matrix: Enter the cost matrix:
999 1 999 2 999 999 999 5 2
999 999 6 999 999 999 5 999 -10
999 999 999 999 1 2 2 -10 999
999 4 999 999 3 999 Enter the source matrix:1
999 999 999 999 999 1 Shortest path:
999 999 999 999 999 999 1->2 cost=5
Enter the source matrix:1 1->3 cost=2
Shortest path:
1->2 cost=1
1->3 cost=7
1->4 cost=2
1->5 cost=5
1->6 cost=6
O5: Enter the number of nodes:5
Enter the cost matrix:
999 3 2 999 4
3 999 8 999 999
2 8 999 1 999
999 999 1 999 3
4 999 999 3 999
Enter the source matrix:1
Shortest path:
1->2 cost=3
1->3 cost=2
1->4 cost=3
1->5 cost=4
Program 11
Floyd’s Algorithm
11. A. Write a Java Program to Implement all pairs shortest paths problem using
Floyd’s algorithm.
Algorithm:
Floyd(d,n)
//Computes shortest distance between all pairs of nodes.
D0 W // initialize D array to W [ ]
for k 1 to n
do for i 1 to n
do for j 1 to n
d[i,j] ← min(d[i,j],d[i,k] + d[k,j])
Program:
import java.util.Scanner;
public class floyd {
{
for (j=1;j<=n;j++)
System.out.print("\t" +c[i][j]);
System.out.println("");
}
}
}
Output:
30 20 0 30 70
60 50 30 0 100
40 50 70 100 0
11. B. Write a Java Program to Implement Travelling Sales Person problem using
Dynamic programming.
Algorithm:
TSP(G, n)
for k := 2 to n do
C({i, k}, k) := d1,k
end for
for s = 3 to n do
for all S ⊆ {1, 2 . . . n} ||S|| = s do
for all k ∈ S do
{C(S, k) = mink,m∈S[C(S − {k}, m) + dm,k]}
Opt: = min[C({1, 2, 3, . . . , n}, k) + d1,k]
end for
end for
end for;
return (opt)
end
Program:
import java.util.Scanner;
publicclass travel {
int tspdp(int c[][],int tour[],int start,int n)
{
int i,j,temp[]=newint[100],mintour[]=newint[100];
int mincost,ccost,k;
if(start==n-2)
return c[tour[n-2]][tour[n-1]]+c[tour[n-1]][0];
mincost=999;
for(i=start+1;i<n;i++)
{
for(j=0;j<n;j++)
temp[j]=tour[j];
temp[start+1]=tour[i];
temp[i]=tour[start+1];
if(c[tour[start]][tour[i]]+(ccost=tspdp(c,tour,start+1,n))<mincost)
{
mincost=c[tour[start]][tour[i]]+ccost;
for(k=0;k<n;k++)
mintour[k]=temp[k];
}
}
for(i=0;i<n;i++)
tour[i]=mintour[i];
return mincost;
}
for(j=0;j<n;j++)
{
c[i][j]=in.nextInt();
if(c[i][j]==0)
c[i][j]=999;
}
for(i=0;i<n;i++)
tour[i]=i;
cost=t.tspdp(c,tour,0,n);
System.out.println("Minimum Cost:"+cost);
System.out.println("Tour:\n");
for(i=0;i<n;i++)
System.out.println(tour[i]+1);
System.out.println("1\n");
}
Output:
Program 12
Subset Problem
12. 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.
Algoritm:
recursiveSubsetSum(s,n)
set Xk = 1 //Try one branch of the tree
if(S + Wk = M)
print vector X //We have a solution
else if ((k + 1 ≤ n) AND (s + Wk ≤ M)
call recursiveSubsetSum( s + Wk, k + 1 )
A solution is still possible, so continue along this branch
if( (k + 1 ≤ n ) AND (s + Wk+1 ≤ M) )
set Xk = 0 //Now try the other branch
call recursiveSubsetSum( s, k + 1 )
Program
import java.util.Scanner;
publicclass subset {
intw[]=newint[20],x[]=newint[20],d;
int i,n,sum=0;
subset s= new subset();
System.out.println("Enter the no. of elements: ");
Scanner in=new Scanner(System.in);
n=in.nextInt();
System.out.println("Enter the elements in increasing order:\n");
for(i=1;i<=n;i++)
s.w[i]=in.nextInt();
System.out.println("Enter the required sum(d): ");
s.d=in.nextInt();
for(i=1;i<=n;i++)
sum+=s.w[i];
if(sum<s.d||s.w[1]>s.d)
System.out.println("Subset not possible!!\n");
else
{
System.out.println("The possible subsets are:\n");
s.subset1(0,1,sum);
}
}
}
Output:
Program 13
Hamiltonian Cycle
13. Design and implement the presence of Hamiltonian Cycle in an undirected Graph
G of n vertices.
Algorithm:
Algorithm Ham
{
Create an empty path array and add vertex 0 to it.
Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether
it is adjacent to the previously added vertex and not already added.
If we find such a vertex, we add the vertex as part of the solution. If we do not find a
vertex then return false.
}
Program:
import java.util.Scanner;
public class Ham
{
static boolean found = false;
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("\t\t\t\tHamiltonian Cycle");
System.out.print("\nEnter the number of the vertices: ");
int n =in.nextInt();
int G[][] =new int[n+1][n+1];
int x[] =new int[n+1];
System.out.print("\nIf edge between the following vertices enter 1 else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
G[i][j] = in.nextInt();
}
for(int i=1;i<=n;i++)
x[i] = 0;
x[1] = 1;
System.out.println("\nSolution:");
Hamiltonian (2,G,x,n);
if (found == false)
System.out.println("No Solution possible!");
}
static void Hamiltonian(int k,int G[][],int x[],int n)
{
while(true)
{
NextValue(k,G,x,n);
if(x[k] == 0)
return;
if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+" ");
System.out.println();
found = true;
return;
}
else
Hamiltonian(k+1,G,x,n);
}
}
static void NextValue(int k,int G[][],int x[],int n)
{
while(true)
{
x[k] = (x[k]+1)%(n+1);
if(x[k] == 0)
return;
if(G[x[k-1]][x[k]] !=0)
{
int j;
for(j=1;j<k;j++)
if(x[k] == x[j])
break;
if(j==k)
if( (k<n) || ( (k==n) && G[x[n]][x[1]] != 0 ) )
return;
}
}
}
}
Output:
10111
11011
11101
11110
Solution:
12345
12435
12534
13245
13425
13524
14235
14325
14523
15234
15324
15423
Program 14
Applet
14. Create an applet which takes name and age as parameters and display the message
“<name> is <age> year old.”
Algorithm:
Algorithm NameAgeApplet
{
Create three textfields and a button.
Read name and age in two textfield and press button.
Write message in format” name is age year old”
}
Program
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=NameAgeApplet width=800 height=1000>
</applet>*/
public class NameAgeApplet extends Applet implements ActionListener
{
TextField name,age,msg;
Button swapEm;
public void init()
{
name = new TextField(35);
age = new TextField(15);
msg=new TextField(45);
swapEm = new Button("click to see message");
swapEm.addActionListener(this);
Output:
Program 15
Factorial Applet
15. Create an applet which takes a number as parameter and display the factorial of
the number.
Algorithm:
Algorithm factapplet
{
Create two textfields and a button.
Read the no in textfield and press button.
Write factorial of the no by converting to integer.
}
Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=factapplet width=800 height=1000>
</applet>*/
public class factapplet extends Applet implements ActionListener
{
TextField no,res;
Button b;
public void init()
{
no = new TextField(35);
res = new TextField(15);
b= new Button("enter");
b.addActionListener(this);
Output:
VIVA QUESTIONS:
SL.NO QUESTION