SlideShare a Scribd company logo
1 of 11
Download to read offline
Please implement in Java. comments would be appreciated 5. Implement Algorithm 6.2 on your
system and run it on the problem instance of Exercise 1.
Solution
Branch and Bound:-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
publicclass BranchandBound
{
staticint[][] wt; // Matrix of edge
// weights
static String[] city; // Vector of city
// names
staticint n; // Dimension for wt
// and city
static ArrayList soln = new ArrayList();
staticint bestTour; // Initialized in
// init()
staticint blocked; // Ditto
staticboolean DEBUG = true; // Show
// accept/reject
// decisions
staticboolean VERBOSE = true; // Show all tours
// discovered
@SuppressWarnings("rawtypes")
privatestaticclass Tour implements Comparable
{
int[] soln;
int index; // In branch-and-bound, start of variable
int dist;
staticint nTours = 0;
// Best-first based on dist, or DFS based on maxheap of index
staticboolean DFS = true;
staticboolean DBG = true;
/*
* Presumable edges up to [index-1] have been verified before
* this constructor has been called. So compute the fixed
* distance from [0] up to [index-1] as dist.
*/
private Tour(int[] vect, int index, int[][] wt)
{
dist = 0;
for (int k = 1; k < index; k++)
// Add edges
dist += wt[vect[k - 1]][vect[k]];
if (index == n)
dist += wt[vect[n - 1]][vect[0]]; // Return edge
soln = newint[n]; // Deep copy
System.arraycopy(vect, 0, soln, 0, n);
this.index = index; // Index to permute
nTours++; // Count up # of tours
if (DBG)
System.out.printf("Idx %d: %s ", index, toString());
}
publicint compareTo(Object o)
{
Tour rt = (Tour) o;
int c1 = rt.index - this.index, c2 = this.dist - rt.dist;
if (DFS)
return c1 == 0 ? c2 : c1;
else
return c2;
}
public String toString()
{
StringBuilder val = new StringBuilder(city[soln[0]]);
for (int k = 1; k < n; k++)
val.append(", " + city[soln[k]]);
val.append(", " + city[soln[0]]);
val.append(String.format(" for %d", dist));
return val.toString();
}
}
privatestaticvoid init(Scanner inp)
{
int sub1, sub2;
String line;
n = inp.nextInt();
wt = newint[n][n];
city = new String[n];
// Initially, there are NO edges; hence -1.
for (sub1 = 0; sub1 < n; sub1++)
Arrays.fill(wt[sub1], -1);
inp.nextLine(); // Discard rest of first line
for (sub1 = 0; sub1 < n; sub1++)
city[sub1] = inp.nextLine();
Arrays.sort(city); // Just to be sure (binarySearch)
inp.nextLine(); // Discard blank spacing line;
blocked = 0; // Accumulate ALL weights for upper bound
while (inp.hasNext())
{
int head, tail;
int dist;
String src, dst;
line = inp.nextLine(); // E.g.: "George" "Pasco" 91
// Chop out the double-quoted substrings.
head = line.indexOf('"') + 1;
tail = line.indexOf('"', head);
src = line.substring(head, tail);
head = line.indexOf('"', tail + 1) + 1;
tail = line.indexOf('"', head);
dst = line.substring(head, tail);
dist = Integer.parseInt(line.substring(tail + 1).trim());
sub1 = Arrays.binarySearch(city, src);
sub2 = Arrays.binarySearch(city, dst);
wt[sub1][sub2] = wt[sub2][sub1] = dist;
blocked += dist;
}
blocked += blocked; // Double the total
bestTour = blocked; // And initialize bestTour
}
// Used below in generating permutations.
privatestaticvoid swap(int[] x, int p, int q)
{
int tmp = x[p];
x[p] = x[q];
x[q] = tmp;
}
// Generate the available tours by branch-and-bound.
// Generate the initial permutation vector, then save that state
// as the first examined in the branch-and-bound.
publicstaticvoid tour()
{
int[] vect = newint[n];
int start;
Queue work = new PriorityQueue();
// First permutation vector.
for (int k = 0; k < n; k++)
vect[k] = k;
start = Arrays.binarySearch(city, "Spokane");
if (start >= 0)
{
vect[start] = 0;
vect[0] = start;
}
work.add(new Tour(vect, 1, wt));
while (!work.isEmpty()) // Branch-and-bound loop
{
Tour current = work.poll();
int index = current.index;
vect = current.soln;
if (index == n) // I.e., Full permutation vector
{
if (wt[vect[n - 1]][vect[0]] > 0) // Return edge?
{
if (current.dist < bestTour) // Better than earlier?
{// Save the state in the list
bestTour = current.dist;
soln.add(current);
if (DEBUG)
System.out.println("Accept " + current);
}
elseif (DEBUG)
System.out.println("Too long: " + current);
}
elseif (DEBUG)
System.out.println("Invalid: " + current);
}
else
// Continue generating permutations
{
int k; // Loop variable
int hold; // Used in regenerating the original state
for (k = index; k < n; k++)
{
swap(vect, index, k);
if (wt[vect[index - 1]][vect[index]] < 0)
continue;
work.add(new Tour(vect, index + 1, wt));
}
// Restore original permutation
hold = vect[index];
for (k = index + 1; k < n; k++)
vect[k - 1] = vect[k];
vect[n - 1] = hold;
}
}
}
@SuppressWarnings("unchecked")
publicstaticvoid main(String[] args) throws Exception
{
String filename = args.length == 0 ? "RoadSet.txt" : args[0];
Scanner inp = new Scanner(new java.io.File(filename));
System.out.println("Data read from file " + filename);
init(inp);
tour();
if (VERBOSE)
{
System.out.println("Tours discovered:");
for (Tour opt : soln)
System.out.println(opt);
}
if (soln.size() == 0)
{
System.out.println("NO tours discovered. Exiting.");
System.exit(0);
}
System.out.println(Tour.nTours + " Tour objects generated.");
Collections.sort(soln);
System.out.println("Best tour: ");
System.out.println(soln.get(0));
}
}
Best First Search:-
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;
publicclass BestFirstSearch
{
private PriorityQueue priorityQueue;
privateint heuristicvalues[];
privateint numberOfNodes;
publicstaticfinalint MAX_VALUE = 999;
public BestFirstSearch(int numberOfNodes)
{
this.numberOfNodes = numberOfNodes;
this.priorityQueue = new PriorityQueue(this.numberOfNodes,
new Vertex());
}
publicvoid bestFirstSearch(int adjacencyMatrix[][], int[] heuristicvalues,int source)
{
int evaluationNode;
int destinationNode;
int visited[] = newint [numberOfNodes + 1];
this.heuristicvalues = heuristicvalues;
priorityQueue.add(new Vertex(source, this.heuristicvalues[source]));
visited[source] = 1;
while (!priorityQueue.isEmpty())
{
evaluationNode = getNodeWithMinimumHeuristicValue();
destinationNode = 1;
System.out.print(evaluationNode + "t");
while (destinationNode <= numberOfNodes)
{
Vertex vertex = new Vertex(destinationNode,this.heuristicvalues[destinationNode]);
if ((adjacencyMatrix[evaluationNode][destinationNode] != MAX_VALUE
&& evaluationNode != destinationNode)&& visited[destinationNode] == 0)
{
priorityQueue.add(vertex);
visited[destinationNode] = 1;
}
destinationNode++;
}
}
}
privateint getNodeWithMinimumHeuristicValue()
{
Vertex vertex = priorityQueue.remove();
return vertex.node;
}
publicstaticvoid main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
int heuristicvalues[];
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = newint[number_of_vertices + 1][number_of_vertices + 1];
heuristicvalues = newint[number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = MAX_VALUE;
}
}
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("Enter the heuristic values of the nodes");
for (int vertex = 1; vertex <= number_of_vertices; vertex++)
{
System.out.print(vertex + ".");
heuristicvalues[vertex] = scan.nextInt();
System.out.println();
}
System.out.println("Enter the source ");
source = scan.nextInt();
System.out.println("The graph is explored as follows");
BestFirstSearch bestFirstSearch = new BestFirstSearch(number_of_vertices);
bestFirstSearch.bestFirstSearch(adjacency_matrix, heuristicvalues,source);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
class Vertex implements Comparator
{
publicint heuristicvalue;
publicint node;
public Vertex(int node, int heuristicvalue)
{
this.heuristicvalue = heuristicvalue;
this.node = node;
}
public Vertex()
{
}
@Override
publicint compare(Vertex vertex1, Vertex vertex2)
{
if (vertex1.heuristicvalue < vertex2.heuristicvalue)
return -1;
if (vertex1.heuristicvalue > vertex2.heuristicvalue)
return 1;
return 0;
}
@Override
publicboolean equals(Object obj)
{
if (obj instanceof Vertex)
{
Vertex node = (Vertex) obj;
if (this.node == node.node)
{
returntrue;
}
}
returnfalse;
}
}

More Related Content

Similar to Please implement in Java. comments would be appreciated 5.pdf

b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdfb. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdfakanshanawal
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Er Ritu Aggarwal
 
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Sean May
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For GoogleEleanor McHugh
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Watch out: Observables are here to stay
Watch out: Observables are here to stayWatch out: Observables are here to stay
Watch out: Observables are here to stayGuilherme Ventura
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Jo Cranford
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdfrushabhshah600
 
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdfganisyedtrd
 

Similar to Please implement in Java. comments would be appreciated 5.pdf (20)

b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdfb. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02
 
Struct examples
Struct examplesStruct examples
Struct examples
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
week-18x
week-18xweek-18x
week-18x
 
week-17x
week-17xweek-17x
week-17x
 
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
The STL
The STLThe STL
The STL
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Watch out: Observables are here to stay
Watch out: Observables are here to stayWatch out: Observables are here to stay
Watch out: Observables are here to stay
 
C++11
C++11C++11
C++11
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
Voce Tem Orgulho Do Seu Codigo
Voce Tem Orgulho Do Seu CodigoVoce Tem Orgulho Do Seu Codigo
Voce Tem Orgulho Do Seu Codigo
 

More from fms12345

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdffms12345
 
Describe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdfDescribe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdffms12345
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdffms12345
 
Could you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdfCould you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdffms12345
 
A piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdfA piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdffms12345
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdffms12345
 
2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdffms12345
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdffms12345
 
1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdffms12345
 
Who are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdfWho are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdffms12345
 
Which company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdfWhich company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdffms12345
 
When multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdfWhen multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdffms12345
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdffms12345
 
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdfWhat does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdffms12345
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdffms12345
 
Using the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdfUsing the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdffms12345
 
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdfUsing Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdffms12345
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdffms12345
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdffms12345
 
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdfThe Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdffms12345
 

More from fms12345 (20)

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
 
Describe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdfDescribe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdf
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
 
Could you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdfCould you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdf
 
A piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdfA piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdf
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
 
2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
 
1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf
 
Who are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdfWho are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdf
 
Which company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdfWhich company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdf
 
When multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdfWhen multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdf
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdf
 
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdfWhat does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdf
 
Using the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdfUsing the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdf
 
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdfUsing Array Approach, Linked List approach, and Delete Byte Approach.pdf
Using Array Approach, Linked List approach, and Delete Byte Approach.pdf
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
 
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdfThe Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Please implement in Java. comments would be appreciated 5.pdf

  • 1. Please implement in Java. comments would be appreciated 5. Implement Algorithm 6.2 on your system and run it on the problem instance of Exercise 1. Solution Branch and Bound:- import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; publicclass BranchandBound { staticint[][] wt; // Matrix of edge // weights static String[] city; // Vector of city // names staticint n; // Dimension for wt // and city static ArrayList soln = new ArrayList(); staticint bestTour; // Initialized in // init() staticint blocked; // Ditto staticboolean DEBUG = true; // Show // accept/reject // decisions staticboolean VERBOSE = true; // Show all tours // discovered
  • 2. @SuppressWarnings("rawtypes") privatestaticclass Tour implements Comparable { int[] soln; int index; // In branch-and-bound, start of variable int dist; staticint nTours = 0; // Best-first based on dist, or DFS based on maxheap of index staticboolean DFS = true; staticboolean DBG = true; /* * Presumable edges up to [index-1] have been verified before * this constructor has been called. So compute the fixed * distance from [0] up to [index-1] as dist. */ private Tour(int[] vect, int index, int[][] wt) { dist = 0; for (int k = 1; k < index; k++) // Add edges dist += wt[vect[k - 1]][vect[k]]; if (index == n) dist += wt[vect[n - 1]][vect[0]]; // Return edge soln = newint[n]; // Deep copy System.arraycopy(vect, 0, soln, 0, n); this.index = index; // Index to permute nTours++; // Count up # of tours if (DBG) System.out.printf("Idx %d: %s ", index, toString()); } publicint compareTo(Object o) { Tour rt = (Tour) o;
  • 3. int c1 = rt.index - this.index, c2 = this.dist - rt.dist; if (DFS) return c1 == 0 ? c2 : c1; else return c2; } public String toString() { StringBuilder val = new StringBuilder(city[soln[0]]); for (int k = 1; k < n; k++) val.append(", " + city[soln[k]]); val.append(", " + city[soln[0]]); val.append(String.format(" for %d", dist)); return val.toString(); } } privatestaticvoid init(Scanner inp) { int sub1, sub2; String line; n = inp.nextInt(); wt = newint[n][n]; city = new String[n]; // Initially, there are NO edges; hence -1. for (sub1 = 0; sub1 < n; sub1++) Arrays.fill(wt[sub1], -1); inp.nextLine(); // Discard rest of first line for (sub1 = 0; sub1 < n; sub1++) city[sub1] = inp.nextLine(); Arrays.sort(city); // Just to be sure (binarySearch) inp.nextLine(); // Discard blank spacing line; blocked = 0; // Accumulate ALL weights for upper bound while (inp.hasNext()) {
  • 4. int head, tail; int dist; String src, dst; line = inp.nextLine(); // E.g.: "George" "Pasco" 91 // Chop out the double-quoted substrings. head = line.indexOf('"') + 1; tail = line.indexOf('"', head); src = line.substring(head, tail); head = line.indexOf('"', tail + 1) + 1; tail = line.indexOf('"', head); dst = line.substring(head, tail); dist = Integer.parseInt(line.substring(tail + 1).trim()); sub1 = Arrays.binarySearch(city, src); sub2 = Arrays.binarySearch(city, dst); wt[sub1][sub2] = wt[sub2][sub1] = dist; blocked += dist; } blocked += blocked; // Double the total bestTour = blocked; // And initialize bestTour } // Used below in generating permutations. privatestaticvoid swap(int[] x, int p, int q) { int tmp = x[p]; x[p] = x[q]; x[q] = tmp; } // Generate the available tours by branch-and-bound. // Generate the initial permutation vector, then save that state // as the first examined in the branch-and-bound. publicstaticvoid tour() { int[] vect = newint[n]; int start;
  • 5. Queue work = new PriorityQueue(); // First permutation vector. for (int k = 0; k < n; k++) vect[k] = k; start = Arrays.binarySearch(city, "Spokane"); if (start >= 0) { vect[start] = 0; vect[0] = start; } work.add(new Tour(vect, 1, wt)); while (!work.isEmpty()) // Branch-and-bound loop { Tour current = work.poll(); int index = current.index; vect = current.soln; if (index == n) // I.e., Full permutation vector { if (wt[vect[n - 1]][vect[0]] > 0) // Return edge? { if (current.dist < bestTour) // Better than earlier? {// Save the state in the list bestTour = current.dist; soln.add(current); if (DEBUG) System.out.println("Accept " + current); } elseif (DEBUG) System.out.println("Too long: " + current); } elseif (DEBUG) System.out.println("Invalid: " + current); } else // Continue generating permutations {
  • 6. int k; // Loop variable int hold; // Used in regenerating the original state for (k = index; k < n; k++) { swap(vect, index, k); if (wt[vect[index - 1]][vect[index]] < 0) continue; work.add(new Tour(vect, index + 1, wt)); } // Restore original permutation hold = vect[index]; for (k = index + 1; k < n; k++) vect[k - 1] = vect[k]; vect[n - 1] = hold; } } } @SuppressWarnings("unchecked") publicstaticvoid main(String[] args) throws Exception { String filename = args.length == 0 ? "RoadSet.txt" : args[0]; Scanner inp = new Scanner(new java.io.File(filename)); System.out.println("Data read from file " + filename); init(inp); tour(); if (VERBOSE) { System.out.println("Tours discovered:"); for (Tour opt : soln) System.out.println(opt); } if (soln.size() == 0) { System.out.println("NO tours discovered. Exiting."); System.exit(0);
  • 7. } System.out.println(Tour.nTours + " Tour objects generated."); Collections.sort(soln); System.out.println("Best tour: "); System.out.println(soln.get(0)); } } Best First Search:- import java.util.Comparator; import java.util.InputMismatchException; import java.util.PriorityQueue; import java.util.Scanner; publicclass BestFirstSearch { private PriorityQueue priorityQueue; privateint heuristicvalues[]; privateint numberOfNodes; publicstaticfinalint MAX_VALUE = 999; public BestFirstSearch(int numberOfNodes) { this.numberOfNodes = numberOfNodes; this.priorityQueue = new PriorityQueue(this.numberOfNodes, new Vertex()); } publicvoid bestFirstSearch(int adjacencyMatrix[][], int[] heuristicvalues,int source) { int evaluationNode; int destinationNode; int visited[] = newint [numberOfNodes + 1]; this.heuristicvalues = heuristicvalues; priorityQueue.add(new Vertex(source, this.heuristicvalues[source]));
  • 8. visited[source] = 1; while (!priorityQueue.isEmpty()) { evaluationNode = getNodeWithMinimumHeuristicValue(); destinationNode = 1; System.out.print(evaluationNode + "t"); while (destinationNode <= numberOfNodes) { Vertex vertex = new Vertex(destinationNode,this.heuristicvalues[destinationNode]); if ((adjacencyMatrix[evaluationNode][destinationNode] != MAX_VALUE && evaluationNode != destinationNode)&& visited[destinationNode] == 0) { priorityQueue.add(vertex); visited[destinationNode] = 1; } destinationNode++; } } } privateint getNodeWithMinimumHeuristicValue() { Vertex vertex = priorityQueue.remove(); return vertex.node; } publicstaticvoid main(String... arg) { int adjacency_matrix[][]; int number_of_vertices; int source = 0; int heuristicvalues[];
  • 9. Scanner scan = new Scanner(System.in); try { System.out.println("Enter the number of vertices"); number_of_vertices = scan.nextInt(); adjacency_matrix = newint[number_of_vertices + 1][number_of_vertices + 1]; heuristicvalues = newint[number_of_vertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = scan.nextInt(); if (i == j) { adjacency_matrix[i][j] = 0; continue; } if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = MAX_VALUE; } } } for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) { adjacency_matrix[j][i] = 1; } } }
  • 10. System.out.println("Enter the heuristic values of the nodes"); for (int vertex = 1; vertex <= number_of_vertices; vertex++) { System.out.print(vertex + "."); heuristicvalues[vertex] = scan.nextInt(); System.out.println(); } System.out.println("Enter the source "); source = scan.nextInt(); System.out.println("The graph is explored as follows"); BestFirstSearch bestFirstSearch = new BestFirstSearch(number_of_vertices); bestFirstSearch.bestFirstSearch(adjacency_matrix, heuristicvalues,source); } catch (InputMismatchException inputMismatch) { System.out.println("Wrong Input Format"); } scan.close(); } } class Vertex implements Comparator { publicint heuristicvalue; publicint node; public Vertex(int node, int heuristicvalue) { this.heuristicvalue = heuristicvalue; this.node = node; } public Vertex() {
  • 11. } @Override publicint compare(Vertex vertex1, Vertex vertex2) { if (vertex1.heuristicvalue < vertex2.heuristicvalue) return -1; if (vertex1.heuristicvalue > vertex2.heuristicvalue) return 1; return 0; } @Override publicboolean equals(Object obj) { if (obj instanceof Vertex) { Vertex node = (Vertex) obj; if (this.node == node.node) { returntrue; } } returnfalse; } }