TreeSet wont add edges - java

i have to code the Dijkstra algorithm. We got a blueprint for this project. Meaning we were told the classes, field variables and methods we have to use.
We have to read the adjacency matrix from a csv file and then use the Dijkstra algorithm.
My problem already begins in in filling the TreeSet edges...
The problem occurs in Graph.class on line 45 when i try to add the Edges.
Example for the csv :
;A;B;C;D;E;F;G;H
A;;1;3;1;;;;
B;1;;;;3;3;;
C;3;;;1;;;1;
D;1;;1;;1;;2;
E;;3;;1;;1;;5
F;;3;;;1;;;1
G;;;1;2;;;;1
H;;;;;5;1;1;
=>
A -> (B,1), (C,3), (D,1)
B -> (A,1), (E,3), (F,3)
C -> (A,3), (D,1), (G,1)
D -> (A,1), (C,1), (E,1), (G,2)
E -> (B,3), (D,1), (F,1), (H,5)
F -> (B,3), (E,1), (H,1)
G -> (C,1), (D,2), (H,1)
H -> (E,5), (F,1), (G,1)
Could somebody look where my problem is ? My indices are correct i checked them with some sout.
Just need help with filling in the TreeSet! I want to try the Dijkstra part myself.
public class Edge implements Comparable<Edge>{
private int distance;
private Node neighbour;
public Edge(int distance, Node neighbour) {
this.distance = distance;
this.neighbour = neighbour;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public Node getNeighbour() {
return neighbour;
}
public void setNeighbour(Node neighbour) {
this.neighbour = neighbour;
}
#Override
public int compareTo(Edge o) {
if (this.neighbour.getId().equals(o.neighbour.getId())){
return 0;
}else{
return -1;
}
}
}
import java.util.TreeSet;
public class Node {
private String id;
private TreeSet<Edge> edges;
private int distance;
private Node previous;
private boolean isVisited;
public Node(String id) {
this.id = id;
this.edges = new TreeSet<>();
}
public Node(String id, int distance){
this.id = id;
this.distance = distance;
}
#Override
public String toString() {
return "Node{" +
"id='" + id + '\'' +
", edges=" + edges +
", distance=" + distance +
", previous=" + previous +
", isVisited=" + isVisited +
'}';
}
public String getPath(){
return null;
}
public void addEdge(Edge e){
edges.add(e);
}
public void init(){
}
public void setStartNode(Node n){
}
public void visit(Node n){
}
public String getId() {
return id;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.util.*;
public class Graph {
private PriorityQueue pq;
private ArrayList<Node> nodes;
public Graph(){
this.pq = new PriorityQueue();
this.nodes = new ArrayList();
}
public void readGraphFromAdjacencyMatrixFile(Path file) throws FileNotFoundException {
Scanner sc = new Scanner(new File(String.valueOf(file)));
ArrayList<String> s = new ArrayList<>();
ArrayList<Character> nodesCharacter = new ArrayList<Character>();
while (sc.hasNext()){
s.add(sc.next());
}
sc.close();
for(char ch: s.get(0).toCharArray()){
if (ch != ';' && ch != ',') {
nodes.add(new Node(Character.toString(ch)));
nodesCharacter.add(ch);
}
}
ArrayList<Node> nodes2 = getNodes();
String node = "";
int index = 0;
for (int i = 1; i < s.size(); i++){
int cnt = -2;
char[] chArray = s.get(i).toCharArray();
for (int j = 0; j < chArray.length; j++){
if(j == 0){
node = String.valueOf(chArray[j]);
index = indexOfNode(String.valueOf((chArray[j])));
}
else if (j >= 2){
if (Character.isDigit(chArray[j])){
int neighbourIndex = indexOfNode("" + nodesCharacter.get(cnt));
Edge e = new Edge(Character.getNumericValue(chArray[j]), nodes.get(neighbourIndex));
nodes.get(index).addEdge(e);
cnt--;
}
}
cnt ++;
}
}
}
public String getAllPAths(){
return null;
}
public void calcWithDijkstra(String startNodeId){
}
public ArrayList<Node> getNodes() {
return nodes;
}
public int indexOfNode(String id){
int cnt = 0;
for (int i = 0; i < nodes.size(); i++){
if (id.equals(nodes.get(i).getId())){
return cnt;
}
cnt++;
}
return -1;
}
}

Related

How to display all elements in a Prefix tree?

I'm trying to print all the word in my prefix tree. I can insert, it's working, but when I try to print all elements of the tree using a preorder way it just gets all messed up. There's some problem on the recursive method PREORDER that I'm using to display all elements.
How can I recursively display all the word on my prefix tree???
public class TrieMain {
public static void main(String[] args) {
TrieTree tree = new TrieTree();
tree.treeInsert("cat");
tree.treeInsert("cattle");
tree.treeInsert("hell");
tree.treeInsert("hello");
tree.treeInsert("rip");
tree.treeInsert("rap");
tree.preorder(tree.getRoot(), "");
}
}
public class TrieTree {
private TrieNode root;
private int wordCount;
public TrieTree() {
this.root = null;
this.wordCount = 0;
}
public TrieNode getRoot() {
return this.root;
}
public void setRoot(TrieNode newRoot) {
this.root = newRoot;
}
public int getWordCount() {
return this.wordCount;
}
public void preorder(TrieNode root, String prefix) {
if (root.getTerminal()) {
System.out.println(prefix);
}
for (int i = 0; i < 26; i++) {
if (root.getCharacters()[i] != '\u0000') {
prefix += root.getCharacters()[i];
preorder(root.getPointers()[i], prefix);
}
}
}
public boolean treeInsert(String word) {
if (this.root == null) {
this.root = new TrieNode();
}
TrieNode temp;
temp = this.root;
int lengthWord = word.length();
for (int i = 0; i < lengthWord; i++) {
int index = getIndex(word.charAt(i));
if (temp.getCharacters()[index] == '\u0000') {
temp.getCharacters()[index] = word.charAt(i);
temp.getPointers()[index] = new TrieNode();
}
temp = temp.getPointers()[index];
}
if (temp.getTerminal()) {
return false;
}
else {
temp.setTerminal(true);
return true;
}
}
public int getIndex(char character) {
int index = ((int) character) - 97;
return index;
}
}
public class TrieNode {
private final int NUM_CHARS = 26;
private char[] characters;
private TrieNode[] pointers;
private boolean terminal;
public TrieNode() {
this.characters = new char[this.NUM_CHARS];
this.pointers = new TrieNode[this.NUM_CHARS];
for (int i = 0; i < this.NUM_CHARS; i++) {
this.characters[i] = '\u0000';
this.pointers[i] = null;
}
this.terminal = false;
}
public char[] getCharacters() {
return this.characters;
}
public TrieNode[] getPointers() {
return this.pointers;
}
public boolean getTerminal() {
return this.terminal;
}
public void setTerminal(boolean newTerminal) {
this.terminal = newTerminal;
}
}

Java BFS Webcrawler produces duplicated website links

I am tasked with creating a Java BFS Algorithm without using the built-in LinkedList and Dynamic ArrayList.
I managed to find 2 examples that seem to achieve the result that I am looking for. They can be found below. When I compare my results to the examples I have found my results seem to have duplicated links.
I suspect it has something to do with my contains() method however having tried many different options that I found from Java: Implement String method contains() without built-in method contains() the issue still persist.
Could someone pls help me with this? Thank you so much in advance!!
Examples
https://github.com/theexplorist/WebCrawler
https://www.youtube.com/watch?v=lyVjfz2Tuck&ab_channel=SylvainSaurel (The code in the video can be found below)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebCrawler {
public static Queue<String> queue = new LinkedList<>();
public static Set<String> marked = new HashSet<>();
public static String regex = "http[s]*://(\\w+\\.)*(\\w+)";
public static void bfsAlgorithm(String root) throws IOException{
queue.add(root);
BufferedReader br = null;
while (!queue.isEmpty()){
String crawledUrl = queue.poll();
System.out.println("\n=== Site crawled : " + crawledUrl + " ===");
if(marked.size() > 100)
return;
boolean ok = false;
URL url = null;
while(!ok){
try{
url = new URL(crawledUrl);
br = new BufferedReader(new InputStreamReader(url.openStream()));
ok = true;
} catch (MalformedURLException e) {
System.out.println("*** Maformed URL : " + crawledUrl);
crawledUrl = queue.poll();
ok = false;
}
}
StringBuilder sb = new StringBuilder();
String tmp = null;
while((tmp = br.readLine()) != null){
sb.append(tmp);
}
tmp = sb.toString();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(tmp);
while (matcher.find()){
String w = matcher.group();
if(!marked.contains(w)){
marked.add(w);
System.out.println("Sited added for crawling : " + w);
queue.add(w);
}
}
}
if(br != null){
br.close();
}
}
public static void showResults(){
System.out.println("\n\nResults : ");
System.out.println("Web sites crawled : " + marked.size() + "\n");
for (String s: marked){
System.out.println("* " + s);
}
}
public static void main(String[] args){
try{
bfsAlgorithm("https://www.tesla.com/");
showResults();
} catch (IOException e) {
}
}
}
Below are the results for the root url: https://en.wikipedia.org/
I edited the code to only show the first 20 links.
Result from https://github.com/theexplorist/WebCrawler
Result from the Youtube Video
Result from my code
If you look at my result you will see that there are duplicated links.
Pls find my code below
Main.java
public static void main(String[] args) {
WebCrawler crawler = new WebCrawler();
String rootUrl = "https://en.wikipedia.org/";
crawler.discoverWeb(rootUrl);
}
}
DA.java (Dynamic Array)
class DA{
int size;
int capacity = 10;
Object[] nameofda;
public DA(){
this.nameofda = new Object[capacity];
}
public DA(int capacity){
this.capacity = capacity;
this.nameofda = new Object[capacity];
}
public void add(Object anything){
if(size >= capacity){
grow();
}
nameofda[size] = anything;
size++;
}
public void insert(int index, Object anything){
if(size >= capacity){
grow();
}
for (int i = size; i > index; i--){
nameofda[i] = nameofda[i - 1];
}
nameofda[index] = anything;
size++;
}
public void delete(Object anything){
for(int i = 0; i < size; i++){
if(nameofda[i] == anything){
for(int j = 0; j < (size - i - 1); j++){
nameofda[i + j] = nameofda[i + j + 1];
}
nameofda[size - 1] = null;
size--;
if(size <=(int)(capacity/3)){
shrink();
}
break;
}
}
}
public boolean contains(Object anything){
for(int i = 0; i < size; i++){
if (nameofda[i] == anything){
return true;
}
}
return false;
}
private void grow(){
int newcap = (int)(capacity *2);
Object[] newnameofda = new Object[newcap];
for(int i = 0; i < size; i++){
newnameofda[i] = nameofda[i];
}
capacity = newcap;
nameofda = newnameofda;
}
private void shrink(){
int newcap = (int)(capacity / 2);
Object[] newnameofda = new Object[newcap];
for(int i = 0; i < size; i++){
newnameofda[i] = nameofda[i];
}
capacity = newcap;
nameofda = newnameofda;
}
public boolean isEmpty(){
return size == 0;
}
public String toString(){
String nameofstring = "";
for(int i = 0; i < size; i++){
nameofstring += nameofda[i] + ", ";
}
if(nameofstring != ""){
nameofstring = "[" + nameofstring.substring(0, nameofstring.length() - 2) + "]";
}
else {
nameofstring = "[]";
}
return nameofstring;
}
Queue.java (LinkedList)
public class Queue<T> {
private Node<T> front;
private Node<T> rear;
private int length;
private static class Node<T> {
private final T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
public void enQueue(T item) {
if (front == null) {
rear = new Node<T>(item);
front = rear;
} else {
rear.next = new Node<T>(item);
rear = rear.next;
}
length++;
}
public T deQueue() {
if (front != null) {
T item = front.data;
front = front.next;
length--;
return item;
}
return null;
}
public int size() {
return length;
}
public boolean isEmpty(){
return length == 0;
}
public void displayQueue() {
Node<T> currentNode = front;
while (currentNode != null) {
System.out.print(currentNode.data+" ");
currentNode = currentNode.next;
}
}
}
WebCrawler.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebCrawler {
private Queue<String> queue;
DA discoveredWebsitesList = new DA(5);
public WebCrawler() {
this.queue = new Queue<>();
}
public void discoverWeb(String root) {
this.queue.enQueue(root);
this.discoveredWebsitesList.add(root);
while (!queue.isEmpty()) {
String v = this.queue.deQueue();
StringBuilder rawHtml = readUrl(v);
String regexe = "https://(\\w+\\.)*(\\w+)";
Pattern pattern = Pattern.compile(regexe);
Matcher matcher = pattern.matcher(rawHtml);
while(matcher.find()){
String actualUrl = matcher.group();
if(!this.discoveredWebsitesList.contains(actualUrl)){
this.discoveredWebsitesList.add(actualUrl);
System.out.println("website has been found with URL :" + actualUrl);
this.queue.enQueue(actualUrl);
//System.out.println("Size is: " + queue.size());
if(queue.size() == 20){
System.exit(0);
}
}
}
}
}
public StringBuilder readUrl(String v) {
StringBuilder rawHtml = new StringBuilder() ;
URL ur;
try {
ur = new URL(v);
BufferedReader br = new BufferedReader(new InputStreamReader(ur.openStream()));
String inputLine = "";
while((inputLine = br.readLine()) != null){
rawHtml.append(inputLine);
}br.close();
} catch (Exception e) {
e.printStackTrace();
}
return rawHtml;
}
}

A star algorithm using a Node class and a graph class

I am coding an A* algorithm and the algorithm needs a node class to access the nodes and a graph class to be able to draw the graph. The algorithm should be able to show the path from the starting node to the end node and should be able to know the matrix equivalent of it. Here is the code I currently have are:
A Star algorithm class:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class A_star extends Node {
public Node[][] searchArea;
public PriorityQueue<Node> openList;
public boolean[][] closedList;
public static Node startNode;
public static Node endNode;
public Node currentNode;
public Node prevNode;
public final int V_H_Cost = 2;
public final int DIAGONAL_COST = 3;
public A_star(Node[][] graph , Node startNode, Node endNode){
super();
searchArea = new Node[row][col];
this.closedList = new boolean[row][col];
this.openList = new PriorityQueue<Node>((Node n1, Node n2) -> {
return Integer.compare(n1.f, n2.f);
});
A_star.startNode = startNode;
A_star.endNode = endNode;
for(int i = 0; i < searchArea.length; i++){
for(int j = 0; j < searchArea[startNode.getRow()].length; j++){
searchArea[i][j] = new Node(i, j);
searchArea[i][j].calculateH(endNode);
searchArea[i][j].visited = false;
}
}
searchArea[startNode.getRow()][startNode.getCol()].f = 0;
for (int i = 0; i < graph.length; i++) {
addBlock(graph[i][0], graph[i][1]);
}
}
public void addBlock(Node i, Node j){
searchArea[i.getRow()][j.getCol()] = null;
}
public void updateCost(Node currentNode, Node t, int cost){
int tFinalCost = t.h + cost;
boolean isOpen = openList.contains(t);
if(!isOpen || tFinalCost < t.f){
t.f = tFinalCost;
t.prev = currentNode;
if(!isOpen)
openList.add(t);
}
}
public void findPath(Node startNode, Node endNode){
ArrayList<Node> path;
path = getPath(currentNode);
System.out.println("path");
for(int i = 0; i < path.size(); i++){
System.out.println(path.get(i));
}
startNode.setG(0);
startNode.calculateH(endNode);
startNode.calculateF();
openList.add(startNode);
while (true){
currentNode = openList.poll();
if(currentNode == null)
break;
closedList[currentNode.getRow()][currentNode.getCol()] = true;
if(currentNode.getRow() == endNode.getRow() && currentNode.getCol() == endNode.getCol())
return;
Node t;
if(currentNode.getRow() - 1 >= 0){
t = searchArea[currentNode.getRow()][currentNode.getCol()];
updateCost(currentNode, t,currentNode.f + V_H_Cost);
if(currentNode.getCol() - 1 >= 0){
t = searchArea[currentNode.getRow() - 1][currentNode.getCol() - 1];
updateCost(currentNode, t,currentNode.f + DIAGONAL_COST);
}
else if(currentNode.getCol() + 1 < searchArea[0].length){
t = searchArea[currentNode.getRow() - 1][currentNode.getCol() + 1];
updateCost(currentNode, t,currentNode.f + DIAGONAL_COST);
}
}
if(currentNode.getCol() - 1 >= 0){
t = searchArea[currentNode.getRow()][currentNode.getCol() - 1];
updateCost(currentNode, t,currentNode.f + V_H_Cost);
}
if(currentNode.getCol() + 1 < searchArea[0].length){
t = searchArea[currentNode.getRow()][currentNode.getCol() + 1];
updateCost(currentNode, t,currentNode.f + V_H_Cost);
}
if(currentNode.getRow() + 1 < searchArea[0].length) {
t = searchArea[currentNode.getRow() + 1][currentNode.getCol()];
updateCost(currentNode, t,currentNode.f + V_H_Cost);
if(currentNode.getCol() - 1 >= 0){
t = searchArea[currentNode.getRow() + 1][currentNode.getCol() - 1];
updateCost(currentNode, t,currentNode.f + DIAGONAL_COST);
}
else if (currentNode.getCol() + 1 < searchArea[0].length){
t = searchArea[currentNode.getRow() + 1][currentNode.getCol() + 1];
updateCost(currentNode, t,currentNode.f + DIAGONAL_COST);
}
}
}
}
public ArrayList<Node> getPath(Node currentNode){
ArrayList<Node> path = new ArrayList<>();
if(closedList[endNode.getRow()][endNode.getCol()]){
currentNode = searchArea[endNode.getRow()][endNode.getCol()];
System.out.print(currentNode);
searchArea[currentNode.row][currentNode.col].visited = true;
while(currentNode.prev != null){
System.out.println(currentNode.prev);
searchArea[currentNode.getRow()][currentNode.getCol()].visited = true;
currentNode = currentNode.prev;
}
path.add(currentNode);
}
else
System.out.println("No Possible Path");
return path;
}
static Node[][] graph = new Node[][] { { new Node(0, 0), new Node(2, 1), new Node(2,2), new Node(3, 3), new Node(0, 4) },
{ new Node(2, 5), new Node(0, 6), new Node(3, 7), new Node(2, 8), new Node(0, 9) },
{ new Node(2, 10), new Node(3, 11), new Node(0, 12), new Node(2, 13), new Node(0, 14)},
{ new Node(3, 15), new Node(2, 16), new Node(2, 17), new Node(0, 18), new Node(3, 19) },
{ new Node(0, 20), new Node(0, 21), new Node(0, 22), new Node(3, 23), new Node(0, 24) } };
//static Graph h = new Graph(graph);
public static void main(String[] args){
startNode = new Node(0, 0);
endNode = new Node(4, 4);
A_star A = new A_star(graph, startNode, endNode);
A.findPath(startNode, endNode);
A.getPath(startNode);
}
The Node class:
public class Node {
public Node prev, next;
public int g;
public int h;
public int f;
public boolean isBlock;
public int row, col;
static int id;
public boolean visited;
public Node(int i, int j) {
}
public Node getPrev(){
return prev;
}
public void setPrev(Node prev){
this.prev = prev;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
public Node(){
super();
row = 5;
col = 7;
this.id = id;
}
public int getID(){
return id;
}
public void setID(int n){
id = n;
}
public int getRow(){
return row;
}
public void setRow(int row){
this.row = row;
}
public int getCol(){
return col;
}
public void setCol(int col){
this.col = col;
}
public void calculateH(Node endNode){
this.h = Math.abs(endNode.row - this.row) + Math.abs(endNode.col - this.col);
}
public void calculateG(Node startNode){
this.g = Math.abs(startNode.row - this.row) + Math.abs(startNode.col - this.col);
}
public void calculateF(){
this.f = getH() + getH();
setF(f);
}
public int getH(){
return h;
}
public void setH(int h){
this.h = h;
}
public int getG(){
return g;
}
public void setG(int g){
this.g = g;
}
public int getF(){
return f;
}
public void setF(int f){
this.f = f;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isBlock(){
return isBlock;
}
public void setBlock(boolean isBlock){
this.isBlock = isBlock;
}
}
The graph class:
import java.util.*;
public class Graph extends Node {
LinkedList<Node> nodes; //adj list
ArrayList<LinkedList<Node>> adjList; //other adj list for bfs
int[][] matrix;//matrix to traverse throuhg
Node[] nodeMatrix; //to retrieve the nodes from
Node[][] adjMatrix; // I added this for Dijkstra
Set<Node> allNodes; //set of all nodes in the graph
public Graph(LinkedList<Node> adj, Set<Node> s) {
nodes = adj;
allNodes = s;
}
public Graph(int[][] m, Node[] n) {
matrix = m;
nodeMatrix = n;
}
public Graph(Node[][] g) {
adjMatrix = g;
}
public Graph() {
}
public Graph(ArrayList<LinkedList<Node>> a) {
adjList = a;
}
public ArrayList<LinkedList<Node>> getAdjList() {
return adjList;
}
}
The algorithm class currently does not print the path and I am confused why it does not print.
Feel free to code as much as possible.

Can't access the object within the GraphNode

I have a graph that contains objects of type GraphNodes. These nodes contain an object City that has properties if It's infected or not. I want to loop through all the nodes and check if a city is infected or not. I have a generic method getInfo which returns an object of type E in my case City. But when i try to chain another method or to get property i can't see them as if they are not available. All the classes in the code are from college so i can't add/remove methods. I've tried with foreach but I still can't get the methods.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.LinkedList;
class City {
String osnovna_granka;
boolean zarazen;
City(String osnovna_granka, boolean zarazen) {
this.osnovna_granka = osnovna_granka;
this.zarazen = zarazen;
}
#Override
public String toString() {
if (zarazen == true) {
return osnovna_granka + " zarazen";
} else {
return osnovna_granka + " nezarazen";
}
}
}
class Graph {
int num_nodes;
GraphNode<City> adjList[];
#SuppressWarnings("unchecked")
public Graph(int num_nodes) {
this.num_nodes = num_nodes;
adjList = (GraphNode<City>[]) new GraphNode[num_nodes];
}
int adjacent(int x, int y) {
// proveruva dali ima vrska od jazelot so
// indeks x do jazelot so indeks y
return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
}
void addEdge(int x, int y) {
// dodava vrska od jazelot so indeks x do jazelot so indeks y
if (!adjList[x].containsNeighbor(adjList[y])) {
adjList[x].addNeighbor(adjList[y]);
}
}
void deleteEdge(int x, int y) {
adjList[x].removeNeighbor(adjList[y]);
}
#Override
public String toString() {
String ret = new String();
for (int i = 0; i < this.num_nodes; i++) {
ret += i + ": " + adjList[i] + "\n";
}
return ret;
}
}
class GraphNode<E> {
private int index;//index (reden broj) na temeto vo grafot
private E info;
private LinkedList<GraphNode<E>> neighbors;
public GraphNode(int index, E info) {
this.index = index;
this.info = info;
neighbors = new LinkedList<GraphNode<E>>();
}
boolean containsNeighbor(GraphNode<E> o) {
return neighbors.contains(o);
}
void addNeighbor(GraphNode<E> o) {
neighbors.add(o);
}
void removeNeighbor(GraphNode<E> o) {
if (neighbors.contains(o)) {
neighbors.remove(o);
}
}
#Override
public String toString() {
String ret = "INFO:" + info + " SOSEDI:";
for (int i = 0; i < neighbors.size(); i++) {
ret += neighbors.get(i).info + " ";
}
return ret;
}
#Override
public boolean equals(Object obj) {
#SuppressWarnings("unchecked")
GraphNode<E> pom = (GraphNode<E>) obj;
return (pom.info.equals(this.info));
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public E getInfo() {
return info;
}
public void setInfo(E info) {
this.info = info;
}
public LinkedList<GraphNode<E>> getNeighbors() {
return neighbors;
}
public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
this.neighbors = neighbors;
}
}
public class Main {
public static void main(String[] args) throws Exception {
int i, j, k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Graph g = new Graph(N);
for (i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
st.nextToken();
String osnovna_granka = st.nextToken();
String str_zarazen = st.nextToken();
if (str_zarazen.equals("zarazen")) {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, true));
} else {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, false));
}
}
int M = Integer.parseInt(br.readLine());
for (i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
g.addEdge(a, b);
g.addEdge(b, a);
}
br.close();
Stack<GraphNode> stack = new Stack<>();
int counter = 0;
// vasiot kod ovde;
for(GraphNode gn: g.adjList) {
gn.getInfo().// Here the properties of City should show up
}
}
}
GraphNode is a generic type and you have not specified the type, the IDE cannot infer the type so no methods can be suggested. in the for loop you need to specify the type of the GraphNode.
for(GraphNode<City> gn: g.adjList)

How to write a toString method for a weighted undirected graph in java?

I have written a class for the undirected graphs and a symbol table to convert edges from strings to numbers and vise versa but the two string method is not working as i get a stack overflow error. i have implemented a LinkedStack which is the same as a stack in java's library. I am not getting a compilation error and I would appreciate it if could look at the toString method. the other methods are working fine. here is the code below. I think the problem is when i call the iterator
public class EdgeWeightedGraph {
private final int V;
private int E;
private LinkedStack<Edge>[] adj;
public EdgeWeightedGraph(int V){
this.V = V;
this.E = 0;
adj = new LinkedStack[V];
for (int v = 0; v < V; v++)
{
adj[v] = new LinkedStack<Edge>();
}
}
public int V(){
return V(); // This was the error. thank you for spotting it :)
}
public int E(){
return E;
}
public int degree(int v){
return adj[v].size();
}
public void addEdge(Edge e){
int v = e.either();
int w = e.other(v);
adj[v].push(e);
adj[w].push(e);
E++;
}
public Iterable<Edge> adj(int v){
return adj[v];
}
public Iterable<Edge> edges(){
LinkedStack<Edge> b = new LinkedStack<Edge>();
for(int v = 0; v < V; v++)
{
for(Edge e: adj[v])
{
if(e.other(v) > v)
b.push(e);
}
}
return b;
}
}
as for the othe class which contains the toString()
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class EdgeSymbolGraph {
private ST<String, Integer> st;
private String[] keys;
private EdgeWeightedGraph G;
public EdgeSymbolGraph(File stream){
st = new ST<String, Integer>();
try
{
Scanner in = new Scanner(stream);
while(in.hasNextLine())
{
String v1 = in.next();
String v2 = in.next();
if(!st.contains(v1))
st.put(v1, st.size());
if(!st.contains(v2))
st.put(v2, st.size());
}
keys = new String[st.size()];
for(String name: st.keys())
keys[st.get(name)] = name;
G = new EdgeWeightedGraph(st.size());
Scanner m = new Scanner(stream);
for(int i = 0; m.hasNextLine(); i++)
{
int v1 = st.get(m.next());
int v2 = st.get(m.next());
Edge e = new Edge(v1, v2, i);
G.addEdge(e);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public EdgeWeightedGraph getGraph(){
return G;
}
public String name(int v){
return keys[v];
}
public int index(String s){
return st.get(s);
}
public String toString(){ //this the method that needs fixing
StringBuilder s = new StringBuilder();
s.append(G.V() + " " + G.E() + "\n");
for (int v = 0; v < G.V(); v++)
{
s.append(name(v) + " : ");
for (Edge e: G.adj(v)) // I think this is the problem when i call iterator
{
s.append(e.toString() + " ");
}
s.append("\n");
}
return s.toString();
}
}
Your definition of the method V() is recursive and probably is going into an infinite loop. You probably want it to be:
public int V(){
return V;
}

Categories