I am trying to create a graph file .I have to read in values from a .gra file(which I think is a .txt file).We were told to tokenise lines based on a space in the format <vertex> <name> <x-coord> <y-coord>,same for edge
I had a look at a couple of related questions,but still cant find the answer.
Here's the code I was given:
public EdgeListVertex(V element) {
this.element = element;
}
#Override
public V element() {
return element;
}
public String toString() {
return element.toString();
}
}
private class EdgeListEdge implements Edge<E> {
Position<EdgeListEdge> position;
E element;
EdgeListVertex start, end;
public EdgeListEdge(EdgeListVertex start, EdgeListVertex end, E element) {
this.start = start;
this.end = end;
this.element = element;
}
#Override
public E element() {
return element;
}
public String toString() {
return element.toString();
}
}
private List<EdgeListVertex> vertices;
private List<EdgeListEdge> edges;
public EdgeListGraph() {
vertices = new LinkedList<EdgeListVertex>();
edges = new LinkedList<EdgeListEdge>();
}
#SuppressWarnings("unchecked")
#Override
public Vertex<V>[] endVertices(Edge<E> e) {
EdgeListEdge edge = (EdgeListEdge) e;
Vertex<V>[] endpoints = (Vertex<V>[]) new Vertex[2];
endpoints[0] = edge.start;
endpoints[1] = edge.end;
return endpoints;
}
#Override
public Vertex<V> opposite(Vertex<V> v, Edge<E> e) {
Vertex<V>[] endpoints = endVertices(e);
if (endpoints[0].equals(v)) {
return endpoints[1];
} else if (endpoints[1].equals(v)) {
return endpoints[0];
}
throw new InvalidVertexException();
}
#Override
public boolean areAdjacent(Vertex<V> v, Vertex<V> w) {
for (EdgeListEdge edge: edges) {
if ((edge.start.equals(v)) && (edge.end.equals(w))) return true;
if ((edge.end.equals(v)) && (edge.start.equals(w))) return true;
}
return false;
}
#Override
public V replace(Vertex<V> v, V x) {
EdgeListVertex vertex = (EdgeListVertex) v;
V temp = vertex.element;
vertex.element = x;
return temp;
}
#Override
public E replace(Edge<E> e, E x) {
EdgeListEdge edge = (EdgeListEdge) e;
E temp = edge.element;
edge.element = x;
return temp;
}
#Override
public Vertex<V> insertVertex(V v) {
EdgeListVertex vertex = new EdgeListVertex(v);
Position<EdgeListVertex> position = vertices.insertLast(vertex);
vertex.position = position;
return vertex;
}
#Override
public Edge<E> insertEdge(Vertex<V> v, Vertex<V> w, E o) {
EdgeListEdge edge = new EdgeListEdge((EdgeListVertex) v, (EdgeListVertex) w, o);
Position<EdgeListEdge> position = edges.insertLast(edge);
edge.position = position;
return edge;
}
#Override
public V removeVertex(Vertex<V> v) {
Iterator<Edge<E>> it = incidentEdges(v).iterator();
while (it.hasNext()) it.remove();
EdgeListVertex vertex = (EdgeListVertex) v;
vertices.remove(vertex.position);
return vertex.element;
}
#Override
public E removeEdge(Edge<E> e) {
EdgeListEdge edge = (EdgeListEdge) e;
edges.remove(edge.position);
return edge.element;
}
#Override
public List<Edge<E>> incidentEdges(Vertex<V> v) {
LinkedList<Edge<E>> list = new LinkedList<Edge<E>>();
for (EdgeListEdge edge : edges) {
if (edge.start.equals(v)) list.insertLast(edge);
if (edge.end.equals(v)) list.insertLast(edge);
}
return list;
}
#Override
public List<Vertex<V>> vertices() {
LinkedList<Vertex<V>> list = new LinkedList<Vertex<V>>();
for (EdgeListVertex vertex : vertices) {
list.insertLast(vertex);
}
return list;
}
#Override
public List<Edge<E>> edges() {
LinkedList<Edge<E>> list = new LinkedList<Edge<E>>();
for (EdgeListEdge edge : edges) {
list.insertLast(edge);
}
return list;
}
}
Any tips?
A good approach might be to create a new class with fields for vertex, name and coordinates. Then read in the data from a scanner into an ArrayList of the class you just created. After this, you could just pass the ArrayList into whatever you are using for graphing (which might require a few tweaks).
Example scanner code (untested):
File graphFile = new File(filepath);
Scanner graphScanner = new Scanner(graphFile);
Then, to read from the scanner (untested):
ArrayList<graphClass> dataPoints = new ArrayList<graphClass>(); //you will have to make graphClass
while(graphScanner.hasNextLine()) {
dataPoints.add(new graphClass(graphScanner.nextDouble(), graphScanner.next(), graphScanner.nextDouble(), graphScanner.nextDouble()); //assuming constructor of graphClass takes vertex, name, x, y in that order
I hope this helps.
Related
I have a while(whiteSet.size()>0) check in my code and inside the while block I call dfs method. The method modifies the HashSet. Why does the while loop never gives an error?
public class CycleInDG {
Set<Vertex> whiteSet = new HashSet<>();
Set<Vertex> greySet = new HashSet<>();
Set<Vertex> blackSet = new HashSet<>();
List<Integer> cyclePath = new ArrayList<>();
Map<Vertex, Vertex> parentMap = new HashMap<>();
Graph g = new Graph();
public boolean hasCycle() {
Map<Integer, Vertex> map = g.getGraphMap();
Collection<Vertex> vertices = map.values();
for (Vertex vertex : vertices) {
whiteSet.add(vertex);
}
while(whiteSet.size()>0) {
parentMap.clear();
if(dfs(whiteSet.iterator().next(), null)) {
return true;
}
}
return false;
}
public boolean dfs(Vertex current, Vertex parent) {
moveVertex(current, whiteSet, greySet);
for (Vertex vertex : current.getNeighbors()) {
if(blackSet.contains(vertex)) {
continue;
}
if(greySet.contains(vertex)) {
parentMap.put(vertex, current);
return true;
}
parentMap.put(vertex, current);
boolean result = dfs(vertex, current);
if(result) {
return result;
}
}
moveVertex(current, greySet, blackSet);
return false;
}
public void moveVertex(Vertex v, Set<Vertex> src, Set<Vertex> dest) {
src.remove(v);
dest.add(v);
}
}
I want to create a Queue after the FIFO rule, every element is created at the end of the queue but my getNext() for the element don't work(the Value is null) and I have no clue.
Here is the UML:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyLinkedQueue<E> implements Iterable<E>, MyQueue<E> {
private Cell front;
private Cell rear;
private int count;
public Cell getFront() {
return front;
}
public void setFront(Cell front) {
this.front = front;
}
public Cell getRear() {
return rear;
}
public void setRear(Cell rear) {
this.rear = rear;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public class Cell {
private E value;
private Cell next;
Cell(E element) {
this.value = element;
}
public E getValue() {
return value;
}
public void setValue(E value) {
this.value = value;
}
public Cell getNext() {
return next;
}
public void setNext(Cell next) {
this.next = next;
}
}
public class MyIterator implements Iterator<E> {
private Cell pointer;
private boolean begin;
private boolean removable;
public Cell getPointer() {
return pointer;
}
public void setPointer(Cell pointer) {
this.pointer = pointer;
}
public boolean isBegin() {
return begin;
}
public void setBegin(boolean begin) {
this.begin = begin;
}
public boolean isRemovable() {
return removable;
}
public void setRemovable(boolean removable) {
this.removable = removable;
}
public MyIterator() {
}
public boolean hasNext() {
return pointer != null ? true : false;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
E e = pointer.value;
pointer = pointer.getNext();
return e;
}
public void remove() {
throw new NoSuchElementException();
}
}
public boolean isEmpty() {
return count == 0;
}
public E peek() throws NoSuchElementException {
E result = null;
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
result = front.getValue();
}
return result;
}
public E peekLast() throws NoSuchElementException {
E result = null;
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
result = rear.getValue();
}
return result;
}
public MyQueue<E> append(E element) {
if (front == null)
front = new Cell(element);
rear = new Cell(element);
// rear=rear.getNext(); getNext() PROBLEM
count++;
return this;
}
public E delete() throws NoSuchElementException {
E e;
e = front.getValue();
// front = front.getNext();getNext() PROBLEM
count--;
if (count == 0)
rear = null;
return e;
}
public int size() {
return count;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (E e : this)
s.append(e + "; ");
return s.toString();
}
#Override
public Iterator<E> iterator() {
Iterator<E> iterator = new MyIterator();
return iterator;
}
}
I have problem to implement the transpose of a graph using only Adjacency List, without Edge List. Every vertex of the graph has a positional list that stores adjacent vertexes. When you have to transpose the graph, every element stored in a list of a vertex A, has to be removed and used as a source vertex. So if we have the situation
A -> B
B after its removal, add to its own adjacent list the old source Vertex A
We have as result:
B -> A
when I update the lists, i override the last information stored in, so I lose connection between vertexes.
public class Vertice implements Comparable<Vertice>{
public Vertice(int valore){
this.valore = valore;
this.color = Color.WHITE;
this.distanza = 0;
this.padre = null;
adiacenze = new NodePositionList<Vertice>();
}
public int getValore() {
return valore;
}
public void setValore(int valore) {
this.valore = valore;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position<Vertice> getPadre() {
return padre;
}
public void setPadre(Position<Vertice> padre) {
this.padre = padre;
}
public int getDistanza() {
return distanza;
}
public void setDistanza(int distanza) {
this.distanza = distanza;
}
public enum Color{
BLACK, WHITE, GREY;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("v_" + valore );
return sb.toString();
}
public boolean equals(Vertice v){
return this.compareTo(v) == 0;
}
#Override
public int compareTo(Vertice o) {
return this.valore - o.getValore();
}
public int getFin() {
return fin;
}
public void setFin(int fin) {
this.fin = fin;
}
public Position<Vertice> getRiferimentoVertice() {
return riferimentoVertice;
}
public void setRiferimentoVertice(Position<Vertice> riferimentoVertice) {
this.riferimentoVertice = riferimentoVertice;
}
public Iterable<Vertice> getAdiacenze() {
return adiacenze;
}
public void setAdiacenze(NodePositionList<Vertice> adiacenze) {
this.adiacenze = adiacenze;
}
public Position<Vertice> addNodoAdiacente(Vertice v){
Position<Vertice> newVertice = adiacenze.addLast(v);
v.setRiferimentoAsAdiacenza(newVertice);
return newVertice;
}
public Position<Vertice> removeNodoAdiacente(Position<Vertice> v){
return adiacenze.remove(v);
}
public Position<Vertice> getRiferimentoAsAdiacenza() {
return riferimentoAsAdiacenza;
}
public void setRiferimentoAsAdiacenza(Position<Vertice> riferimentoAsAdiacenza) {
this.riferimentoAsAdiacenza = riferimentoAsAdiacenza;
}
public boolean hasAdiacent(){
return adiacenze.size() == 0;
}
public boolean hasRedEdge(){
return redEdge;
}
public void setHasRedEdge(boolean redEdge){
this.redEdge = redEdge;
}
private boolean redEdge;
private int valore;
private Color color;
private Position<Vertice> padre;
private int distanza;
private int fin;
private Position<Vertice> riferimentoVertice;
private Position<Vertice> riferimentoAsAdiacenza;
private NodePositionList<Vertice> adiacenze;
here the "Grafo.java" class
public class Grafo {
public Grafo(int numV){
verticiGrafo = new NodePositionList<Vertice>();
listaArchi = new NodePositionList<Arco>();
this.V = numV;
}
public Position<Vertice> addVertice(Vertice v){
Position<Vertice> newAdded = verticiGrafo.addLast(v);
v.setRiferimentoVertice(newAdded);
return newAdded;
}
public NodePositionList<Vertice> getVertici(){
return verticiGrafo;
}
public Position<Arco> addArco(Arco a){
a.getSorgente().element().addNodoAdiacente(a.getDestinazione().element());
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> connect(Position<Vertice> sorgente, Position<Vertice> destinazione){
Arco a = new Arco(sorgente, destinazione);
Vertice v_sorgente = sorgente.element();
Vertice v_destinazione = destinazione.element();
v_sorgente.addNodoAdiacente(v_destinazione);
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> removeArco(Position<Arco> a){
a.element().getSorgente().element().removeNodoAdiacente(a.element().getDestinazione());
return listaArchi.remove(a);
}
public Iterable<Arco> archi(){
return listaArchi;
}
public void invertiArco(Position<Arco> a){
Arco a1 = a.element();
Position<Vertice> temp = a1.getDestinazione();
a1.setDestinazione(a1.getSorgente());
a1.setSorgente(temp);
Vertice sorgente = a1.getSorgente().element();
Vertice destinatario = a1.getDestinazione().element();
sorgente.addNodoAdiacente(destinatario);
}
public Position<Arco> getArcoByVertici(Position<Vertice> sorgente, Position<Vertice> destinazione){
for(Arco a: listaArchi){
if(a.getColor() == EdgeColor.NONE){
Vertice dest = a.getDestinazione().element();
Vertice sorg = a.getSorgente().element();
if(sorg.equals(sorgente.element()) && dest.equals(destinazione.element())){
return a.getRiferimentoArco();
}
}
}
return null;
}
public void removeAllAdiacenze(){
for(Vertice v: this.getVertici()){
v.setAdiacenze( new NodePositionList<Vertice>());
}
}
public void setColorArco(Position<Arco> a, EdgeColor ec){
a.element().setColor(ec);
}
public NodePositionList<Arco> getListaArchi() {
return listaArchi;
}
public void setListaArchi(NodePositionList<Arco> listaArchi) {
this.listaArchi = listaArchi;
}
private NodePositionList<Vertice> verticiGrafo;
private NodePositionList<Arco> listaArchi; //lista archi uscenti
public final int V;
}
here the method on the "Ricerca.java" class that I'm trying to make
public static Grafo traspostaGrafo(Grafo g){
NodePositionList<Vertice> npl = g.getVertici();
Position<Vertice> u = npl.first();
while (u != npl.getTail()){
u.element().setColor(Color.WHITE);
NodePositionList<Vertice> adiacenti = g.getListaAdiacenti(u.element().getValore());
Position<Vertice> adiacente = adiacenti.first();
while (adiacente != adiacenti.getTail() && adiacente.element().getFlag() == 0){
g.addNodoAdiacente(adiacente.element(), u.element());
g.removeNodoAdiacente(adiacente);
adiacente = adiacenti.next(adiacente);
u.element().setFlag(1);
}
}
return g
}
Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}
I have created a priority queue using the Java API and I want to remove a specific element from the priority queue at the end of the program. I know it has to do something with the comparator but I can't figure it out. Can someone help? Here's my code:
public static void main(String[] args)
{
PriorityQueue<Element> X = new PriorityQueue<Element>(100, new ElementComparator());
X.add(new Element(30, 3));
X.add(new Element(700, 4.5));
X.add(new Element(100, 6.2));
X.add(new Element(2, 8.1));
System.out.println(X.remove(new Element(100, 6.2)));
}
and here's my Element class:
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;};
public double getValue() { return value;};
public void setValue(double v) { value = v;};
And here's the comparator that I created:
public int compare(Element o1, Element o2)
{
int idx1 = o1.getIndex();
int idx2 = o2.getIndex();
if (idx1 < idx2) {
return -1;
} else if (idx1 > idx2) {
return 1;
} else {
return 0;
}
}
public boolean equals(Element o1, Element o2)
{
return o1.getIndex() == o2.getIndex();
}
I appreciate your help...
You need to define equals() and hashcode() on your Element object as such:
public class Element{
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;}
public double getValue() { return value;}
public void setValue(double v) { value = v;}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Element)) return false;
Element element = (Element) o;
if (index != element.index) return false;
return true;
}
#Override
public int hashCode() {
return index;
}
}
Defining equals() on the ElementComparator does not perform the same task.