SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
VIDYAVARDHAKA COLLEGE OF ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Mysuru, Karnataka-570002
“DESIGN AND ANALYSIS OF ALGORITHMS LAB MANUAL”
(18CS47)
PREPARED BY:
Prof. NITHIN KUMAR
Asst. Professor, Department of Computer Science & Engineering
VVCE, Mysuru
Email: nithingowda021@vvce.ac.in
1a. 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.
import java.util.Scanner;
class Student
{
String USN, Name, Branch, Phone;
Scanner input = new Scanner (System.in);
void read()
{
System.out.println("Enter Student Details");
System.out.println("Enter USN");
USN = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Branch");
Branch = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
}
void display()
{
System.out.printf("%-20s %-20s %-20s %-20s", USN, Name, Branch,
Phone);
}
}
class Studentdetails
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of student details to be created");
int number = input.nextInt();
Student s[] = new Student[number];
// Read student details into array of student objects
for (int i = 0; i < number; i++)
{
s[i] = new Student();
s[i].read();
}
// Display student information
System.out.printf("%-20s %-20s %-20s %-20s", "USN", "NAME",
"BRANCH", "PHONE");
for (int i = 0; i < number; i++)
{
System.out.println();
s[i].display();
}
input.close();
}
}
1b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(),
and Display() methods to demonstrate its working.
import java.util.*;
class arrayStack
{
int arr[];
int top, max;
arrayStack( int n)
{
max = n;
arr = new int[max];
top = -1;
}
void push( int i )
{
if (top == max - 1)
System.out.println("Stack Overflow");
else
arr[++top] = i;
}
void pop()
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else
{
int element = arr[top--];
System.out.println("Popped Element: " + element);
}
}
void display()
{
System.out.print("nStack = ");
if (top == -1)
{
System.out.print("Emptyn");
return;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
}
class Stack
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Size of Integer Stack ");
int n = scan.nextInt();
boolean done = false;
arrayStack stk = new arrayStack(n);
char ch;
do
{
System.out.println("nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. display");
System.out.println("4. Exit");
int choice = scan.nextInt();
switch (choice)
{
case 1: System.out.println("Enter integer element to push");
stk.push(scan.nextInt());
break;
case 2: stk.pop();
break;
case 3: stk.display();
break;
case 4: done = true;
break;
default: System.out.println("Wrong Entry n ");
break;
}
} while (!done);
}
}
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 categorie.
import java.util.Scanner;
class Staff
{
String StaffID, Name, Phone, Salary;
Scanner input = new Scanner(System.in);
void read()
{
System.out.println("Enter StaffID");
StaffID = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
System.out.println("Enter Salary");
Salary = input.nextLine();
}
void display()
{
System.out.printf("n%-15s", "STAFFID: ");
System.out.printf("%-15s n", StaffID);
System.out.printf("%-15s", "NAME: ");
System.out.printf("%-15s n", Name);
System.out.printf("%-15s", "PHONE:");
System.out.printf("%-15s n", Phone);
System.out.printf("%-15s", "SALARY:");
System.out.printf("%-15s n", Salary);
}
}
class Teaching extends Staff
{
String Domain, Publication;
void read_Teaching()
{
super.read(); // call super class read method
System.out.println("Enter Domain");
Domain = input.nextLine();
System.out.println("Enter Publication");
Publication = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "DOMAIN:");
System.out.printf("%-15s n", Domain);
System.out.printf("%-15s", "PUBLICATION:");
System.out.printf("%-15s n", Publication);
}
}
class Technical extends Staff
{
String Skills;
void read_Technical()
{
super.read(); // call super class read method
System.out.println("Enter Skills");
Skills = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "SKILLS:");
System.out.printf("%-15s n", Skills);
}
}
class Contract extends Staff
{
String Period;
void read_Contract()
{
super.read(); // call super class read method
System.out.println("Enter Period");
Period = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "PERIOD:");
System.out.printf("%-15s n", Period);
}
}
class Staffdetails
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of staff details to be created");
int n = input.nextInt();
Teaching steach[] = new Teaching[n];
Technical stech[] = new Technical[n];
Contract scon[] = new Contract[n];
// Read Staff information under 3 categories
for (int i = 0; i < n; i++)
{
System.out.println("Enter Teaching staff information");
steach[i] = new Teaching();
steach[i].read_Teaching();
}
for (int i = 0; i < n; i++)
{
System.out.println("Enter Technical staff information");
stech[i] = new Technical();
stech[i].read_Technical();
}
for (int i = 0; i < n; i++)
{
System.out.println("Enter Contract staff information");
scon[i] = new Contract();
scon[i].read_Contract();
}
// Display Staff Information
System.out.println("n STAFF DETAILS: n");
System.out.println("-----TEACHING STAFF DETAILS----- ");
for (int i = 0; i < n; i++)
{
steach[i].display();
}
System.out.println();
System.out.println("-----TECHNICAL STAFF DETAILS-----");
for (int i = 0; i < n; i++)
{
stech[i].display();
}
System.out.println();
System.out.println("-----CONTRACT STAFF DETAILS-----");
for (int i = 0; i < n; i++)
{
scon[i].display();
}
input.close();
}
}
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 “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Customer
{
public static void main(String[] args)
{
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name and Date_of_Birth in the format
<Name,DD/MM/YYYY>");
name = scan.next();
// create stringTokenizer with delimiter "/"
StringTokenizer st = new StringTokenizer(name, ",/");
// Count the number of tokens
int count = st.countTokens();
// Print one token at a time and induce new delimiter ","
for (int i = 1; i <= count && st.hasMoreTokens(); i++)
{
System.out.print(st.nextToken());
if (i < count)
System.out.print(",");
}
}
}
3a. Write a Java program to read two integers a and b. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.
import java.util.Scanner;
class exception
{
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: Division by zero.");
}
}
}
3b. Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of cube of
the number.
import java.util.Random;
class SquareThread implements Runnable
{
int x;
SquareThread(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:Square Thread and Square of " + x + " is:
" + x * x);
}
}
class CubeThread implements Runnable
{
int x;
CubeThread(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: " +
x * x * x);
}
}
class RandomThread implements Runnable
{
Random r;
Thread t2, t3;
public void run()
{
int num;
r = new Random();
try
{
while (true)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is "
+ num);
t2 = new Thread(new SquareThread(num));
t2.start();
t3 = new Thread(new CubeThread(num));
t3.start();
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println("Interrupted Exception");
}
}
}
public class MainThread
{
public static void main(String[] args)
{
RandomThread thread_obj = new RandomThread();
Thread t1 = new Thread(thread_obj);
t1.start();
}
}
4. Sort a given set of elements using the quick sort method and determine the time
required to sort the elements. Repeat the experiment for different values of n, the
number of elements in the 1st to be sorted and plot a graph of the time taken versus
n. The elements can be read from a file or can be generated using the random
number generator.
import java.util.Random;
import java.util.Scanner;
public class Quicksort
{
static final int MAX = 10005;
static int[] a = new int[MAX];
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Max array size: ");
int n = input.nextInt();
Random random = new Random();
System.out.println("Enter the array elements: ");
for (int i = 0; i < n; i++)
a[i] = random.nextInt(1000);
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
long startTime = System.nanoTime();
QuickSortAlgorithm(0, n - 1);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("Time Complexity (ms) for n = " + n + " is : " +
(double)elapsedTime / 1000000);
System.out.println("Sorted Array (Quick Sort):");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
input.close();
}
public static void QuickSortAlgorithm(int p, int r)
{
int i, j, temp, pivot;
if (p < r)
{
i = p;
j = r;
pivot = a[p];
while(true)
{
i++;
while (a[i] < pivot && i<r)
{
i++;
}
while (a[j] > pivot)
{
j--;
}
if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
break;
}
}
a[p] = a[j];
a[j] = pivot;
QuickSortAlgorithm(p, j - 1);
QuickSortAlgorithm(j + 1, r);
}
}
}
5. Implement a merge sort algorithm to sort a given set of elements and determine
the time required to sort the elements. Repeat the experiment for different values
of n, the number of elements in the list to be sorted and plot a graph of the time
taken versus n. The elements can be read from a file or can be generated using the
random number generator.
import java.util.Random;
import java.util.Scanner;
public class Mergesort
{
static final int MAX = 10005;
static int[] a = new int[MAX];
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Max array size: ");
int n = input.nextInt();
Random random = new Random();
System.out.println("Enter the array elements: ");
for (int i = 0; i < n; i++)
a[i] = random.nextInt(1000);
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
long startTime = System.nanoTime();
MergeSortAlgo(0, n - 1);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("Time Complexity (ms) for n = " + n + " is : " +
(double)elapsedTime / 1000000);
System.out.println("Sorted Array (Merge Sort):");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
input.close();
}
public static void MergeSortAlgo(int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
MergeSortAlgo(low, mid);
MergeSortAlgo(mid + 1, high);
Merge(low, mid, high);
}
}
public static void Merge(int low, int mid, int high)
{
int[] b = new int[MAX];
int i, h, j, k;
h = i = low;
j = mid + 1;
while ((h <= mid) && (j <= high))
if (a[h] < a[j])
b[i++] = a[h++];
else
b[i++] = a[j++];
if (h > mid)
for (k = j; k <= high; k++)
b[i++] = a[k];
else
for (k = h; k <= mid; k++)
b[i++] = a[k];
for (k = low; k <= high; k++)
a[k] = b[k];
}
}
6a. Implement Fractional Knapsack problem using Greedy Technique.
import java.util.Scanner;
public class Gknapsack {
static int n;
static float capacity, item[], weight[], profit[], ratio[];
public static void main(String args[])
{
int i, j;
float temp;
Scanner in = new Scanner(System.in);
System.out.println("n Enter the number of objects ");
n = in.nextInt();
item=new float[n];
weight=new float[n];
profit=new float[n];
ratio=new float[n];
System.out.println("n Enter items, weights and profit ");
for(i=0; i<n; i++)
{
item[i]=in.nextFloat();
weight[i]=in.nextFloat();
profit[i]=in.nextFloat();
}
System.out.println("n Enter the capacity of knapsack ");
capacity = in.nextFloat();
for(i=0; i<n; i++)
{
ratio[i]= profit[i]/weight[i];
}
for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
if(ratio[i]<ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = item[j];
item[j] = item[i];
item[i] = temp;
}
knapsack();
in.close();
}
public static void knapsack()
{
float tp = 0;
float u = capacity;
int i;
float x[]= new float[n];
for(i=0; i<n; i++)
{
x[i]=0;
}
for(i=0;i<n;i++)
{
if(weight[i]>u)
break;
else
{
x[i]=1;
tp = tp + profit[i];
u = (u-weight[i]);
}
}
if(i<n)
{
x[i]=u/weight[i];
tp = tp +(x[i] * profit[i]);
}
System.out.println("n The resultant vector is");
for(i=0; i<n; i++)
{
System.out.println("item"+(int)item[i]+":"+x[i]);
}
System.out.println("Maximum profit is "+tp);
}
}
6b. Implement 0/1 Knapsack problem using Dynamic Programming.
import java.util.Scanner;
public class Dknapsack {
static int n, m, w[], v[][],value[];
public static int knap(int i,int j)
{
if(i==0||j==0)
{
v[i][j] = 0;
}
else if(j<w[i])
{
v[i][j] = knap(i-1,j);
}
else
{
v[i][j] = Math.max(knap(i-1,j),value[i]+knap(i-1,j-w[i]));
}
return v[i][j];
}
public static void optimal(int i,int j)
{
if(i>=1 || j>=1) {
if(v[i][j]!=v[i-1][j])
{
System.out.println("Item : "+i);
j = j-w[i];
optimal(i-1,j);
}
else
{
optimal(i-1,j);
}
}
}
public static void main(String[] args) {
int profit,i;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of items:");
n = in.nextInt();
System.out.println("Enter the capacity of the knapsack:");
m = in.nextInt();
w=new int[n+1];
value=new int[n+1];
v=new int[n+1][m+1];
System.out.println("nEnter weights:");
for(i=1; i<=n; i++)
{
w[i]=in.nextInt();
}
System.out.println("nEnter profits:");
for(i=1; i<=n; i++)
{
value[i]=in.nextInt();
}
profit = knap(n,m);
System.out.println("Profit: "+profit);
System.out.println("Items to be added for Optimal Solution:");
optimal(n,m);
in.close();
}
}
7. From a given source vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra’s algorithm.
import java.util.Scanner;
public class Dijakstras {
static int a[][];
static int n;
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of vertices:");
n = in.nextInt();
System.out.println("Enter the cost adjacency matrix");
a = new int[n][n];
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
a[i][j] = in.nextInt();
}
}
System.out.println("nEnter the source vertex");
int s=in.nextInt();
Dijkstra(s);
in.close();
}
public static void Dijkstra(int s)
{
int visited[] = new int[n];
int d[] = new int[n];
int i,u,v;
for(i=0;i<n;i++)
{
visited[i]=0;
d[i] = a[s][i];
}
visited[s]=1;
d[s]=0;
i=1;
while(i<=n-1)
{
u = Extract_Min(visited,d);
visited[u]=1;
i++;
for(v=0;v<n;v++)
{
if((d[u]+a[u][v]<d[v]) && visited[v]==0)
d[v]= d[u]+a[u][v];
}
}
for(i=0;i<n;i++)
{
if(i!=s)
System.out.println(s+"->"+i+":"+d[i]);
}
}
public static int Extract_Min(int visited[],int d[])
{
int i,j=0,min=999;
for(i=0;i<n;i++)
if(d[i]<min && visited[i]==0)
{
min = d[i];
j=i;
}
return j;
}
}
8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s
algorithm.
import java.util.Scanner;
public class Kruskals {
static int n, parent[], a[][];
public static int find(int p)
{
while(parent[p]!=0)
{
p=parent[p];
}
return p;
}
public static void union(int i, int j)
{
if(i<j)
parent[i]=j;
else
parent[j]=i;
}
public static void kruskal()
{
int u=0,v=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=999;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(a[i][j]<min && i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
union(i,j);
System.out.println(u+","+v+"=>"+a[u][v]);
sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=999;
}
System.out.println("The cost of minimum spanning tree = "+sum);
}
public static void main(String[] args)
{
int i,j;
System.out.println("Enter the number of vertices of the graph");
Scanner in=new Scanner(System.in);
n=in.nextInt();
a=new int[n][n];
parent=new int[n];
System.out.println("Enter the weighted matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=in.nextInt();
}
}
kruskal();
in.close();
}
}
9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
import java.util.Arrays;
import java.util.Scanner;
public class Prims {
static int a[][];
static int V;
public static void main(String args[])
{
System.out.println("Enter the number of verticesn");
Scanner scanner = new Scanner(System.in);
V = scanner.nextInt();
a = new int[V][V];
System.out.println("Enter the Cost Matrix n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
a[i][j] = scanner.nextInt();
}
}
Prim();
scanner.close();
}
public static void Prim()
{
int no_edge=0,sum=0;
boolean[] selected = new boolean[V];
Arrays.fill(selected, false);
selected[0] = true;
System.out.println("Edge : Weight");
while (no_edge < V - 1)
{
int x=0,y=0,min = 999;
for (int i = 0; i < V; i++)
{
if (selected[i] == true)
{
for (int j = 0; j < V; j++)
{
if (!selected[j] && a[i][j] != 0)
{
if (min > a[i][j])
min = a[i][j];
x=i;
y=j;
}
}
}
}
System.out.println(x + " - " + y + " : " + a[x][y]);
sum=sum+a[x][y];
selected[y] = true;
no_edge++;
}
System.out.println("Cost of Tree: "+sum);
}
}
10. Implement All-Pairs Shortest Paths Problem using Floyds algorithm.
import java.util.Scanner;
public class Floyds
{
static int a[][];
static int n;
public static void main(String args[])
{
System.out.println("Enter the number of verticesn");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
a = new int[n][n];
System.out.println("Enter the Cost Matrix (999 for infinity) n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = scanner.nextInt();
}
}
getPath();
PrintMatrix();
scanner.close();
}
public static void getPath()
{
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((a[i][k] + a[k][j]) < a[i][j])
a[i][j] = a[i][k] + a[k][j];
}
}
public static void PrintMatrix()
{
System.out.println("The All Pair Shortest Path Matrix is:n");
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
System.out.print(a[i][j] +" ");
System.out.println();
}
}
}
10b. Implementation of Travelling Salesperson problem
import java.util.Scanner;
public class TravSalesPerson
{
static int MAX = 100;
static final int infinity = 999;
public static void main(String args[])
{
int cost = infinity;
int c[][] = new int[MAX][MAX];
int tour[] = new int[MAX];
int n;
System.out.println("Travelling Salesman Problem using Dynamic
Programmingn");
System.out.println("Enter number of cities: ");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
System.out.println("Enter Cost matrix:n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
c[i][j] = scanner.nextInt();
if (c[i][j] == 0)
c[i][j] = 999;
}
for (int i = 0; i < n; i++)
tour[i] = i;
cost = tspdp(c, tour, 0, n);
// print tour cost and tour
System.out.println("Minimum Tour Cost: " + cost);
System.out.println("nTour:");
for (int i = 0; i < n; i++)
{
System.out.print(tour[i] + " -> ");
}
System.out.println(tour[0] + "n");
scanner.close();
}
static int tspdp(int c[][], int tour[], int start, int n)
{
int i, j, k;
int temp[] = new int[MAX];
int mintour[] = new int[MAX];
int mincost;
int cost;
if (start == n - 2)
return c[tour[n - 2]][tour[n - 1]] + c[tour[n - 1]][0];
mincost = infinity;
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]] + (cost = tspdp(c, temp, start + 1, n)) <
mincost)
{
mincost = c[tour[start]][tour[i]] + cost;
for (k = 0; k < n; k++)
mintour[k] = temp[k];
}
}
for (i = 0; i < n; i++)
tour[i] = mintour[i];
return mincost;
}
}
11. Implement a subset concept for 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}. A suitable message is to be displayed
if the given problem instance doesn’t have a solution.
import java.util.Scanner;
public class SumofSubset {
static int n, S[], soln[], d;
public static void main(String args[])
{
int sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of elements: ");
n = scanner.nextInt();
S = new int[n+1];
soln = new int[n+1];
System.out.println("Enter the set in increasing order: ");
for (int i = 1; i <= n; i++)
{
S[i] = scanner.nextInt();
}
System.out.println("Enter the max. subset value(d): ");
d = scanner.nextInt();
for (int i = 1; i <= n; i++)
{
sum = sum + S[i];
}
if (sum < d || S[1] > d)
{
System.out.println("No Subset possible");
}
else
{
SumofSub(0, 0, sum);
}
scanner.close();
}
public static void SumofSub(int i, int weight, int total)
{
if (promising(i, weight, total) == true)
if (weight == d)
{
for (int j = 1; j <= n; j++)
{
if (soln[j] == 1)
System.out.print(S[j] + " ");
}
System.out.println();
}
else
{
soln[i+1] = 1;
SumofSub(i+1, weight + S[i+1], total - S[i+1]);
soln[i+1] = 0;
SumofSub(i+1, weight, total - S[i+1]);
}
}
public static boolean promising(int i, int weight, int total)
{
return ((weight + total >= d) && (weight == d || weight + S[i+1] <= d));
}
}
12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
import java.util.Scanner;
public class Hamiltonian
{
boolean found = false;
int G[][];
int x[];
int n;
public static void main(String args[])
{
Hamiltonian hamiltonian = new Hamiltonian();
hamiltonian.getData();
System.out.println("nSolution:");
hamiltonian.HamiltonianMethod(2);
hamiltonian.printNoSlnPossible();
}
public void printNoSlnPossible()
{
if (found == false)
System.out.println("No Solution possible!");
}
public void getData()
{
Scanner scanner = new Scanner(System.in);
System.out.println("ttttHamiltonian Cycle");
System.out.print("nEnter the number of the vertices: ");
n = scanner.nextInt();
G = new int[n + 1][n + 1];
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++)
{
if ((i != j) && (i < j))
{
System.out.print(i + " and " + j + ": ");
G[j][i] = G[i][j] = scanner.nextInt();
}
if (i == j)
G[i][j] = 0;
}
for (int i = 1; i <= n; i++)
x[i] = 0;
x[1] = 1;
scanner.close();
}
void HamiltonianMethod(int k)
{
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(x[1]);
System.out.println();
found = true;
return;
}
else
HamiltonianMethod(k + 1);
}
}
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;
}
}
}
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

C++ student management system
C++ student management systemC++ student management system
C++ student management system
 
OOP Assignment 03.pdf
OOP Assignment 03.pdfOOP Assignment 03.pdf
OOP Assignment 03.pdf
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
List in Python
List in PythonList in Python
List in Python
 
Compiler Design Unit 2
Compiler Design Unit 2Compiler Design Unit 2
Compiler Design Unit 2
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Job sequencing with Deadlines
Job sequencing with DeadlinesJob sequencing with Deadlines
Job sequencing with Deadlines
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Sets in python
Sets in pythonSets in python
Sets in python
 
DAA 18CS42 VTU CSE
DAA 18CS42 VTU CSEDAA 18CS42 VTU CSE
DAA 18CS42 VTU CSE
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Knapsack Problem (DP & GREEDY)
Knapsack Problem (DP & GREEDY)Knapsack Problem (DP & GREEDY)
Knapsack Problem (DP & GREEDY)
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 

Ähnlich wie VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru.pdf

Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptxKimVeeL
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfarihantmum
 
information Security.docx
information Security.docxinformation Security.docx
information Security.docxSouravKarak1
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdfanupamfootwear
 
Lab101.pptx
Lab101.pptxLab101.pptx
Lab101.pptxKimVeeL
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming AssignmentCoding Assignment Help
 
CountPositiveNumbersInArray.javapackage org.students;import java.pdf
CountPositiveNumbersInArray.javapackage org.students;import java.pdfCountPositiveNumbersInArray.javapackage org.students;import java.pdf
CountPositiveNumbersInArray.javapackage org.students;import java.pdfaparnatiwari291
 
when I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxwhen I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxlashandaotley
 
Star pattern programs in java Print Star pattern in java and print triangle ...
Star pattern programs in java Print Star pattern in java and  print triangle ...Star pattern programs in java Print Star pattern in java and  print triangle ...
Star pattern programs in java Print Star pattern in java and print triangle ...Hiraniahmad
 
import java.uti-WPS Office.docx
import java.uti-WPS Office.docximport java.uti-WPS Office.docx
import java.uti-WPS Office.docxKatecate1
 
MagicSquareTest.java import java.util.Scanner;public class Mag.pdf
MagicSquareTest.java import java.util.Scanner;public class Mag.pdfMagicSquareTest.java import java.util.Scanner;public class Mag.pdf
MagicSquareTest.java import java.util.Scanner;public class Mag.pdfanjanacottonmills
 

Ähnlich wie VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru.pdf (20)

Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptx
 
Java final lab
Java final labJava final lab
Java final lab
 
3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
 
information Security.docx
information Security.docxinformation Security.docx
information Security.docx
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Lab101.pptx
Lab101.pptxLab101.pptx
Lab101.pptx
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Java practical
Java practicalJava practical
Java practical
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
WAP to add two given matrices in Java
WAP to add two given matrices in JavaWAP to add two given matrices in Java
WAP to add two given matrices in Java
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming Assignment
 
JAVA.pdf
JAVA.pdfJAVA.pdf
JAVA.pdf
 
CountPositiveNumbersInArray.javapackage org.students;import java.pdf
CountPositiveNumbersInArray.javapackage org.students;import java.pdfCountPositiveNumbersInArray.javapackage org.students;import java.pdf
CountPositiveNumbersInArray.javapackage org.students;import java.pdf
 
when I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxwhen I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docx
 
Java
JavaJava
Java
 
Star pattern programs in java Print Star pattern in java and print triangle ...
Star pattern programs in java Print Star pattern in java and  print triangle ...Star pattern programs in java Print Star pattern in java and  print triangle ...
Star pattern programs in java Print Star pattern in java and print triangle ...
 
import java.uti-WPS Office.docx
import java.uti-WPS Office.docximport java.uti-WPS Office.docx
import java.uti-WPS Office.docx
 
MagicSquareTest.java import java.util.Scanner;public class Mag.pdf
MagicSquareTest.java import java.util.Scanner;public class Mag.pdfMagicSquareTest.java import java.util.Scanner;public class Mag.pdf
MagicSquareTest.java import java.util.Scanner;public class Mag.pdf
 

Mehr von Nithin Kumar,VVCE, Mysuru

18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Nithin Kumar,VVCE, Mysuru
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruVTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruVTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
 VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,MysuruNithin Kumar,VVCE, Mysuru
 
Vtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCEVtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCENithin Kumar,VVCE, Mysuru
 
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCEVTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCENithin Kumar,VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruNithin Kumar,VVCE, Mysuru
 
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruVTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruNithin Kumar,VVCE, Mysuru
 
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruVTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruNithin Kumar,VVCE, Mysuru
 

Mehr von Nithin Kumar,VVCE, Mysuru (13)

VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
 
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruVTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
 
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruVTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
 
VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
 VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
 
Vtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCEVtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCE
 
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCEVTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
 
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruVTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
 
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruVTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
 

Kürzlich hochgeladen

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 

Kürzlich hochgeladen (20)

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 

VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru.pdf

  • 1. VIDYAVARDHAKA COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Mysuru, Karnataka-570002 “DESIGN AND ANALYSIS OF ALGORITHMS LAB MANUAL” (18CS47) PREPARED BY: Prof. NITHIN KUMAR Asst. Professor, Department of Computer Science & Engineering VVCE, Mysuru Email: nithingowda021@vvce.ac.in
  • 2. 1a. 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. import java.util.Scanner; class Student { String USN, Name, Branch, Phone; Scanner input = new Scanner (System.in); void read() { System.out.println("Enter Student Details"); System.out.println("Enter USN"); USN = input.nextLine(); System.out.println("Enter Name"); Name = input.nextLine(); System.out.println("Enter Branch"); Branch = input.nextLine(); System.out.println("Enter Phone"); Phone = input.nextLine(); } void display() { System.out.printf("%-20s %-20s %-20s %-20s", USN, Name, Branch, Phone); } } class Studentdetails { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number of student details to be created"); int number = input.nextInt(); Student s[] = new Student[number];
  • 3. // Read student details into array of student objects for (int i = 0; i < number; i++) { s[i] = new Student(); s[i].read(); } // Display student information System.out.printf("%-20s %-20s %-20s %-20s", "USN", "NAME", "BRANCH", "PHONE"); for (int i = 0; i < number; i++) { System.out.println(); s[i].display(); } input.close(); } } 1b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate its working. import java.util.*; class arrayStack { int arr[]; int top, max; arrayStack( int n) { max = n; arr = new int[max]; top = -1; } void push( int i ) { if (top == max - 1) System.out.println("Stack Overflow"); else arr[++top] = i; } void pop() {
  • 4. if (top == -1) { System.out.println("Stack Underflow"); } else { int element = arr[top--]; System.out.println("Popped Element: " + element); } } void display() { System.out.print("nStack = "); if (top == -1) { System.out.print("Emptyn"); return; } for (int i = top; i >= 0; i--) System.out.print(arr[i] + " "); System.out.println(); } } class Stack { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter Size of Integer Stack "); int n = scan.nextInt(); boolean done = false; arrayStack stk = new arrayStack(n); char ch; do { System.out.println("nStack Operations"); System.out.println("1. push"); System.out.println("2. pop"); System.out.println("3. display"); System.out.println("4. Exit"); int choice = scan.nextInt(); switch (choice) { case 1: System.out.println("Enter integer element to push"); stk.push(scan.nextInt()); break;
  • 5. case 2: stk.pop(); break; case 3: stk.display(); break; case 4: done = true; break; default: System.out.println("Wrong Entry n "); break; } } while (!done); } }
  • 6. 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 categorie. import java.util.Scanner; class Staff { String StaffID, Name, Phone, Salary; Scanner input = new Scanner(System.in); void read() { System.out.println("Enter StaffID"); StaffID = input.nextLine(); System.out.println("Enter Name"); Name = input.nextLine(); System.out.println("Enter Phone"); Phone = input.nextLine(); System.out.println("Enter Salary"); Salary = input.nextLine(); } void display() { System.out.printf("n%-15s", "STAFFID: "); System.out.printf("%-15s n", StaffID); System.out.printf("%-15s", "NAME: "); System.out.printf("%-15s n", Name); System.out.printf("%-15s", "PHONE:"); System.out.printf("%-15s n", Phone); System.out.printf("%-15s", "SALARY:"); System.out.printf("%-15s n", Salary); } } class Teaching extends Staff { String Domain, Publication; void read_Teaching() { super.read(); // call super class read method
  • 7. System.out.println("Enter Domain"); Domain = input.nextLine(); System.out.println("Enter Publication"); Publication = input.nextLine(); } void display() { super.display(); // call super class display() method System.out.printf("%-15s", "DOMAIN:"); System.out.printf("%-15s n", Domain); System.out.printf("%-15s", "PUBLICATION:"); System.out.printf("%-15s n", Publication); } } class Technical extends Staff { String Skills; void read_Technical() { super.read(); // call super class read method System.out.println("Enter Skills"); Skills = input.nextLine(); } void display() { super.display(); // call super class display() method System.out.printf("%-15s", "SKILLS:"); System.out.printf("%-15s n", Skills); } } class Contract extends Staff { String Period; void read_Contract() { super.read(); // call super class read method System.out.println("Enter Period"); Period = input.nextLine(); }
  • 8. void display() { super.display(); // call super class display() method System.out.printf("%-15s", "PERIOD:"); System.out.printf("%-15s n", Period); } } class Staffdetails { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number of staff details to be created"); int n = input.nextInt(); Teaching steach[] = new Teaching[n]; Technical stech[] = new Technical[n]; Contract scon[] = new Contract[n]; // Read Staff information under 3 categories for (int i = 0; i < n; i++) { System.out.println("Enter Teaching staff information"); steach[i] = new Teaching(); steach[i].read_Teaching(); } for (int i = 0; i < n; i++) { System.out.println("Enter Technical staff information"); stech[i] = new Technical(); stech[i].read_Technical(); } for (int i = 0; i < n; i++) { System.out.println("Enter Contract staff information"); scon[i] = new Contract(); scon[i].read_Contract(); } // Display Staff Information
  • 9. System.out.println("n STAFF DETAILS: n"); System.out.println("-----TEACHING STAFF DETAILS----- "); for (int i = 0; i < n; i++) { steach[i].display(); } System.out.println(); System.out.println("-----TECHNICAL STAFF DETAILS-----"); for (int i = 0; i < n; i++) { stech[i].display(); } System.out.println(); System.out.println("-----CONTRACT STAFF DETAILS-----"); for (int i = 0; i < n; i++) { scon[i].display(); } input.close(); } } 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 “/”. import java.util.Scanner; import java.util.StringTokenizer; public class Customer { public static void main(String[] args) { String name; Scanner scan = new Scanner(System.in); System.out.println("Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY>"); name = scan.next(); // create stringTokenizer with delimiter "/" StringTokenizer st = new StringTokenizer(name, ",/"); // Count the number of tokens int count = st.countTokens();
  • 10. // Print one token at a time and induce new delimiter "," for (int i = 1; i <= count && st.hasMoreTokens(); i++) { System.out.print(st.nextToken()); if (i < count) System.out.print(","); } } }
  • 11. 3a. Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero. import java.util.Scanner; class exception { 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: Division by zero."); } } } 3b. Write a Java program that implements a multi-thread application that has three threads. First thread generates a random integer for every 1 second; second thread computes the square of the number and prints; third thread will print the value of cube of the number. import java.util.Random; class SquareThread implements Runnable { int x; SquareThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Square Thread and Square of " + x + " is: " + x * x); } }
  • 12. class CubeThread implements Runnable { int x; CubeThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: " + x * x * x); } } class RandomThread implements Runnable { Random r; Thread t2, t3; public void run() { int num; r = new Random(); try { while (true) { num = r.nextInt(100); System.out.println("Main Thread and Generated Number is " + num); t2 = new Thread(new SquareThread(num)); t2.start(); t3 = new Thread(new CubeThread(num)); t3.start(); Thread.sleep(1000); System.out.println("--------------------------------------"); } } catch (Exception ex) { System.out.println("Interrupted Exception"); } }
  • 13. } public class MainThread { public static void main(String[] args) { RandomThread thread_obj = new RandomThread(); Thread t1 = new Thread(thread_obj); t1.start(); } }
  • 14. 4. Sort a given set of elements using the quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the 1st to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. import java.util.Random; import java.util.Scanner; public class Quicksort { static final int MAX = 10005; static int[] a = new int[MAX]; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter Max array size: "); int n = input.nextInt(); Random random = new Random(); System.out.println("Enter the array elements: "); for (int i = 0; i < n; i++) a[i] = random.nextInt(1000); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); long startTime = System.nanoTime(); QuickSortAlgorithm(0, n - 1); long stopTime = System.nanoTime(); long elapsedTime = stopTime - startTime; System.out.println("Time Complexity (ms) for n = " + n + " is : " + (double)elapsedTime / 1000000); System.out.println("Sorted Array (Quick Sort):"); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); input.close(); } public static void QuickSortAlgorithm(int p, int r) { int i, j, temp, pivot; if (p < r) { i = p; j = r; pivot = a[p]; while(true) { i++; while (a[i] < pivot && i<r) {
  • 15. i++; } while (a[j] > pivot) { j--; } if (i < j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } else { break; } } a[p] = a[j]; a[j] = pivot; QuickSortAlgorithm(p, j - 1); QuickSortAlgorithm(j + 1, r); } } }
  • 16. 5. Implement a merge sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. import java.util.Random; import java.util.Scanner; public class Mergesort { static final int MAX = 10005; static int[] a = new int[MAX]; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter Max array size: "); int n = input.nextInt(); Random random = new Random(); System.out.println("Enter the array elements: "); for (int i = 0; i < n; i++) a[i] = random.nextInt(1000); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); long startTime = System.nanoTime(); MergeSortAlgo(0, n - 1); long stopTime = System.nanoTime(); long elapsedTime = stopTime - startTime; System.out.println("Time Complexity (ms) for n = " + n + " is : " + (double)elapsedTime / 1000000); System.out.println("Sorted Array (Merge Sort):"); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); input.close(); } public static void MergeSortAlgo(int low, int high) { int mid; if (low < high) { mid = (low + high) / 2; MergeSortAlgo(low, mid); MergeSortAlgo(mid + 1, high); Merge(low, mid, high); } } public static void Merge(int low, int mid, int high) {
  • 17. int[] b = new int[MAX]; int i, h, j, k; h = i = low; j = mid + 1; while ((h <= mid) && (j <= high)) if (a[h] < a[j]) b[i++] = a[h++]; else b[i++] = a[j++]; if (h > mid) for (k = j; k <= high; k++) b[i++] = a[k]; else for (k = h; k <= mid; k++) b[i++] = a[k]; for (k = low; k <= high; k++) a[k] = b[k]; } }
  • 18. 6a. Implement Fractional Knapsack problem using Greedy Technique. import java.util.Scanner; public class Gknapsack { static int n; static float capacity, item[], weight[], profit[], ratio[]; public static void main(String args[]) { int i, j; float temp; Scanner in = new Scanner(System.in); System.out.println("n Enter the number of objects "); n = in.nextInt(); item=new float[n]; weight=new float[n]; profit=new float[n]; ratio=new float[n]; System.out.println("n Enter items, weights and profit "); for(i=0; i<n; i++) { item[i]=in.nextFloat(); weight[i]=in.nextFloat(); profit[i]=in.nextFloat(); } System.out.println("n Enter the capacity of knapsack "); capacity = in.nextFloat(); for(i=0; i<n; i++) { ratio[i]= profit[i]/weight[i]; } for(i=0; i<n; i++) for(j=i+1; j<n; j++) if(ratio[i]<ratio[j]) { temp = ratio[j]; ratio[j] = ratio[i]; ratio[i] = temp; temp = profit[j]; profit[j] = profit[i]; profit[i] = temp; temp = weight[j]; weight[j] = weight[i]; weight[i] = temp; temp = item[j]; item[j] = item[i]; item[i] = temp;
  • 19. } knapsack(); in.close(); } public static void knapsack() { float tp = 0; float u = capacity; int i; float x[]= new float[n]; for(i=0; i<n; i++) { x[i]=0; } for(i=0;i<n;i++) { if(weight[i]>u) break; else { x[i]=1; tp = tp + profit[i]; u = (u-weight[i]); } } if(i<n) { x[i]=u/weight[i]; tp = tp +(x[i] * profit[i]); } System.out.println("n The resultant vector is"); for(i=0; i<n; i++) { System.out.println("item"+(int)item[i]+":"+x[i]); } System.out.println("Maximum profit is "+tp); } } 6b. Implement 0/1 Knapsack problem using Dynamic Programming. import java.util.Scanner; public class Dknapsack { static int n, m, w[], v[][],value[]; public static int knap(int i,int j) { if(i==0||j==0) {
  • 20. v[i][j] = 0; } else if(j<w[i]) { v[i][j] = knap(i-1,j); } else { v[i][j] = Math.max(knap(i-1,j),value[i]+knap(i-1,j-w[i])); } return v[i][j]; } public static void optimal(int i,int j) { if(i>=1 || j>=1) { if(v[i][j]!=v[i-1][j]) { System.out.println("Item : "+i); j = j-w[i]; optimal(i-1,j); } else { optimal(i-1,j); } } } public static void main(String[] args) { int profit,i; Scanner in = new Scanner(System.in); System.out.println("Enter the number of items:"); n = in.nextInt(); System.out.println("Enter the capacity of the knapsack:"); m = in.nextInt(); w=new int[n+1]; value=new int[n+1]; v=new int[n+1][m+1]; System.out.println("nEnter weights:"); for(i=1; i<=n; i++) { w[i]=in.nextInt(); } System.out.println("nEnter profits:"); for(i=1; i<=n; i++) { value[i]=in.nextInt(); }
  • 21. profit = knap(n,m); System.out.println("Profit: "+profit); System.out.println("Items to be added for Optimal Solution:"); optimal(n,m); in.close(); } }
  • 22. 7. From a given source vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’s algorithm. import java.util.Scanner; public class Dijakstras { static int a[][]; static int n; public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Enter the number of vertices:"); n = in.nextInt(); System.out.println("Enter the cost adjacency matrix"); a = new int[n][n]; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { a[i][j] = in.nextInt(); } } System.out.println("nEnter the source vertex"); int s=in.nextInt(); Dijkstra(s); in.close(); } public static void Dijkstra(int s) { int visited[] = new int[n]; int d[] = new int[n]; int i,u,v; for(i=0;i<n;i++) { visited[i]=0; d[i] = a[s][i]; } visited[s]=1; d[s]=0; i=1; while(i<=n-1) { u = Extract_Min(visited,d); visited[u]=1; i++; for(v=0;v<n;v++) { if((d[u]+a[u][v]<d[v]) && visited[v]==0) d[v]= d[u]+a[u][v];
  • 23. } } for(i=0;i<n;i++) { if(i!=s) System.out.println(s+"->"+i+":"+d[i]); } } public static int Extract_Min(int visited[],int d[]) { int i,j=0,min=999; for(i=0;i<n;i++) if(d[i]<min && visited[i]==0) { min = d[i]; j=i; } return j; } }
  • 24. 8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s algorithm. import java.util.Scanner; public class Kruskals { static int n, parent[], a[][]; public static int find(int p) { while(parent[p]!=0) { p=parent[p]; } return p; } public static void union(int i, int j) { if(i<j) parent[i]=j; else parent[j]=i; } public static void kruskal() { int u=0,v=0,min,k=0,i,j,sum=0; while(k<n-1) { min=999; for(i=0;i<n;i++) for(j=0;j<n;j++) if(a[i][j]<min && i!=j) { min=a[i][j]; u=i; v=j; } i=find(u); j=find(v); if(i!=j) { union(i,j); System.out.println(u+","+v+"=>"+a[u][v]); sum=sum+a[u][v]; k++; } a[u][v]=a[v][u]=999; }
  • 25. System.out.println("The cost of minimum spanning tree = "+sum); } public static void main(String[] args) { int i,j; System.out.println("Enter the number of vertices of the graph"); Scanner in=new Scanner(System.in); n=in.nextInt(); a=new int[n][n]; parent=new int[n]; System.out.println("Enter the weighted matrix"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { a[i][j]=in.nextInt(); } } kruskal(); in.close(); } }
  • 26. 9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm. import java.util.Arrays; import java.util.Scanner; public class Prims { static int a[][]; static int V; public static void main(String args[]) { System.out.println("Enter the number of verticesn"); Scanner scanner = new Scanner(System.in); V = scanner.nextInt(); a = new int[V][V]; System.out.println("Enter the Cost Matrix n"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { a[i][j] = scanner.nextInt(); } } Prim(); scanner.close(); } public static void Prim() { int no_edge=0,sum=0; boolean[] selected = new boolean[V]; Arrays.fill(selected, false); selected[0] = true; System.out.println("Edge : Weight"); while (no_edge < V - 1) { int x=0,y=0,min = 999; for (int i = 0; i < V; i++) { if (selected[i] == true) { for (int j = 0; j < V; j++) { if (!selected[j] && a[i][j] != 0) { if (min > a[i][j]) min = a[i][j]; x=i; y=j; }
  • 27. } } } System.out.println(x + " - " + y + " : " + a[x][y]); sum=sum+a[x][y]; selected[y] = true; no_edge++; } System.out.println("Cost of Tree: "+sum); } }
  • 28. 10. Implement All-Pairs Shortest Paths Problem using Floyds algorithm. import java.util.Scanner; public class Floyds { static int a[][]; static int n; public static void main(String args[]) { System.out.println("Enter the number of verticesn"); Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); a = new int[n][n]; System.out.println("Enter the Cost Matrix (999 for infinity) n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = scanner.nextInt(); } } getPath(); PrintMatrix(); scanner.close(); } public static void getPath() { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if ((a[i][k] + a[k][j]) < a[i][j]) a[i][j] = a[i][k] + a[k][j]; } } public static void PrintMatrix() { System.out.println("The All Pair Shortest Path Matrix is:n"); for(int i=0; i<n; i++) { for(int j=0; j<n; j++) System.out.print(a[i][j] +" "); System.out.println(); } } }
  • 29. 10b. Implementation of Travelling Salesperson problem import java.util.Scanner; public class TravSalesPerson { static int MAX = 100; static final int infinity = 999; public static void main(String args[]) { int cost = infinity; int c[][] = new int[MAX][MAX]; int tour[] = new int[MAX]; int n; System.out.println("Travelling Salesman Problem using Dynamic Programmingn"); System.out.println("Enter number of cities: "); Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); System.out.println("Enter Cost matrix:n"); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = scanner.nextInt(); if (c[i][j] == 0) c[i][j] = 999; } for (int i = 0; i < n; i++) tour[i] = i; cost = tspdp(c, tour, 0, n); // print tour cost and tour System.out.println("Minimum Tour Cost: " + cost); System.out.println("nTour:"); for (int i = 0; i < n; i++) { System.out.print(tour[i] + " -> "); } System.out.println(tour[0] + "n"); scanner.close(); } static int tspdp(int c[][], int tour[], int start, int n) { int i, j, k; int temp[] = new int[MAX]; int mintour[] = new int[MAX]; int mincost;
  • 30. int cost; if (start == n - 2) return c[tour[n - 2]][tour[n - 1]] + c[tour[n - 1]][0]; mincost = infinity; 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]] + (cost = tspdp(c, temp, start + 1, n)) < mincost) { mincost = c[tour[start]][tour[i]] + cost; for (k = 0; k < n; k++) mintour[k] = temp[k]; } } for (i = 0; i < n; i++) tour[i] = mintour[i]; return mincost; } }
  • 31. 11. Implement a subset concept for 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}. A suitable message is to be displayed if the given problem instance doesn’t have a solution. import java.util.Scanner; public class SumofSubset { static int n, S[], soln[], d; public static void main(String args[]) { int sum = 0; Scanner scanner = new Scanner(System.in); System.out.println("Enter number of elements: "); n = scanner.nextInt(); S = new int[n+1]; soln = new int[n+1]; System.out.println("Enter the set in increasing order: "); for (int i = 1; i <= n; i++) { S[i] = scanner.nextInt(); } System.out.println("Enter the max. subset value(d): "); d = scanner.nextInt(); for (int i = 1; i <= n; i++) { sum = sum + S[i]; } if (sum < d || S[1] > d) { System.out.println("No Subset possible"); } else { SumofSub(0, 0, sum); } scanner.close(); } public static void SumofSub(int i, int weight, int total) { if (promising(i, weight, total) == true) if (weight == d) { for (int j = 1; j <= n; j++) { if (soln[j] == 1) System.out.print(S[j] + " "); } System.out.println();
  • 32. } else { soln[i+1] = 1; SumofSub(i+1, weight + S[i+1], total - S[i+1]); soln[i+1] = 0; SumofSub(i+1, weight, total - S[i+1]); } } public static boolean promising(int i, int weight, int total) { return ((weight + total >= d) && (weight == d || weight + S[i+1] <= d)); } }
  • 33. 12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n vertices using backtracking principle. import java.util.Scanner; public class Hamiltonian { boolean found = false; int G[][]; int x[]; int n; public static void main(String args[]) { Hamiltonian hamiltonian = new Hamiltonian(); hamiltonian.getData(); System.out.println("nSolution:"); hamiltonian.HamiltonianMethod(2); hamiltonian.printNoSlnPossible(); } public void printNoSlnPossible() { if (found == false) System.out.println("No Solution possible!"); } public void getData() { Scanner scanner = new Scanner(System.in); System.out.println("ttttHamiltonian Cycle"); System.out.print("nEnter the number of the vertices: "); n = scanner.nextInt(); G = new int[n + 1][n + 1]; 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++) { if ((i != j) && (i < j)) { System.out.print(i + " and " + j + ": "); G[j][i] = G[i][j] = scanner.nextInt(); } if (i == j) G[i][j] = 0; }
  • 34. for (int i = 1; i <= n; i++) x[i] = 0; x[1] = 1; scanner.close(); } void HamiltonianMethod(int k) { 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(x[1]); System.out.println(); found = true; return; } else HamiltonianMethod(k + 1); } } 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; } } } }