To generate an input text file for the WeightedDigraph constructor, you need to follow the format that the constructor expects. The constructor reads the number of vertices first, then the number of edges, followed by the edges themselves in the format source target weight.
Here's an example input text file named input.txt:
5
7
0 1 5.0
0 2 3.0
0 4 10.0
1 3 2.0
2 1 1.0
3 2 4.0
4 3 7.0
Explanation:
- The first line indicates there are 5 vertices.
- The second line indicates there are 7 edges.
- The following 7 lines each describe an edge with a source vertex, a target vertex, and a weight.
Steps to Create the File:
- Open a text editor (e.g., Notepad, VS Code, Sublime Text).
- Copy and paste the content above into the text editor.
- Save the file as
input.txt.
Example Code to Use the File:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
WeightedDigraph graph = new WeightedDigraph("input.txt");
// Additional code to use the graph
}
}
WeightedDigraph Class (for reference):
import java.util.*;
public class WeightedDigraph {
private final int V;
private final Bag<DirectedEdge>[] adj;
public WeightedDigraph(String filename) throws FileNotFoundException {
System.setIn(new FileInputStream(filename));
Scanner in = new Scanner(System.in).useLocale(Locale.US);
V = in.nextInt();
adj = new Bag[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<>();
}
int nE = in.nextInt();
for (int e = 0; e < nE; e++) {
addEdge(in.nextInt(), in.nextInt(), in.nextDouble());
}
}
private void addEdge(int v, int w, double weight) {
adj[v].add(new DirectedEdge(v, w, weight));
}
public Iterable<DirectedEdge> adj(int v) {
return adj[v];
}
public int V() {
return V;
}
private static class DirectedEdge {
private final int v;
private final int w;
private final double weight;
public DirectedEdge(int v, int w, double weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
public int from() {
return v;
}
public int to() {
return w;
}
public double weight() {
return weight;
}
}
private static class Bag<Item> implements Iterable<Item> {
private Node<Item> first;
private int n;
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
public void add(Item item) {
Node<Item> oldfirst = first;
first = new Node<>();
first.item = item;
first.next = oldfirst;
n++;
}
public Iterator<Item> iterator() {
return new ListIterator<>(first);
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() {
return current != null;
}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
}
This setup will allow you to read the graph from the input.txt file and use it within your Java program.