Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please try your best to complete this 11 methods under. I have provided the Undi

ID: 3577457 • Letter: P

Question

Please try your best to complete this 11 methods under.

I have provided the UndirectedGraph class with the single instance data variable.

Do not add any additional instance data variables. Do not modify any other classes provided.

In addition to writing the 8 required methods of the interface and the constructor, you will also write methods for the two traversals and an isConnected method.

import java.util.Queue;


public class UndirectedGraph<T> implements BasicGraphInterface <T> {
  
private DirectedGraph digraph;
  
public UndirectedGraph() {
  
}

public boolean addVertex(T vertexLabel) {
return false;
}

public boolean addEdge(T begin, T end, double edgeWeight) {
return false;
}

  
public boolean addEdge(T begin, T end) {
return false;
}

  
public boolean hasEdge(T begin, T end) {
return false;
}

  
public boolean isEmpty() {
return false;
}

  
public int getNumberOfVertices() {
return 0;
}

  
public int getNumberOfEdges() {
return 0;
}

  
public void clear() {
  
}
  
public Queue<T> getBreadthFirstTraversal(T origin) {
return null;
}
  
public Queue<T> getDepthFirstTraversal(T origin) {
return null;
}
  
  
public boolean isConnected(T origin) {
return false;
}

}

///////////information for the 11 methods

/**
* An interface of methods providing basic operations for directed
* and undirected graphs that are either weighted or unweighted.
*
* @author Frank M. Carrano
* @version 2.0
*/
public interface BasicGraphInterface<T>
{
/** Task: Adds a given vertex to the graph.
* @param vertexLabel an object that labels the new vertex and
* is distinct from the labels of current vertices
* @return true if the vertex is added, or false if not */
public boolean addVertex(T vertexLabel);
  
/** Task: Adds a weighted edge between two given distinct vertices that
* are currently in the graph. The desired edge must not already
* be in the graph. In a directed graph, the edge points
* toward the second vertex given.
* @param begin an object that labels the origin vertex of the edge
* @param end an object, distinct from begin, that labels the end
* vertex of the edge
* @param edgeWeight the real value of the edge's weight
* @return true if the edge is added, or false if not */
public boolean addEdge(T begin, T end, double edgeWeight);
  
/** Task: Adds an unweighted edge between two given distinct vertices
* that are currently in the graph. The desired edge must not
* already be in the graph. In a directed graph, the edge points
* toward the second vertex given.
* @param begin an object that labels the origin vertex of the edge
* @param end an object, distinct from begin, that labels the end
* vertex of the edge
* @return true if the edge is added, or false if not */
public boolean addEdge(T begin, T end);
  
/** Task: Sees whether an edge exists between two given vertices.
* @param begin an object that labels the origin vertex of the edge
* @param end an object that labels the end vertex of the edge
* @return true if an edge exists */
public boolean hasEdge(T begin, T end);
  
/** Task: Sees whether the graph is empty.
* @return true if the graph is empty */
public boolean isEmpty();
  
/** Task: Gets the number of vertices in the graph.
* @return the number of vertices in the graph */
public int getNumberOfVertices();
  
/** Task: Gets the number of edges in the graph.
* @return the number of edges in the graph */
public int getNumberOfEdges();
  
/** Task: Removes all vertices and edges from the graph. */
public void clear();

} // end BasicGraphInterface

///////////////////////////// information

import java.util.Iterator;
import java.util.Stack;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.PriorityQueue;

/**
* A class that implements the ADT directed graph.
*
* @author Frank M. Carrano
* @version 2.0
*/
public class DirectedGraph<T> implements BasicGraphInterface <T>, java.io.Serializable {
   private DictionaryInterface<T, VertexInterface<T>> vertices;
   private int edgeCount;

   public DirectedGraph() {
       vertices = new LinkedDictionary<T, VertexInterface<T>>();
       edgeCount = 0;
   } // end default constructor

   public boolean addVertex(T vertexLabel) {
       VertexInterface<T> isDuplicate = vertices.add(vertexLabel, new Vertex(
               vertexLabel));
       return isDuplicate == null; // was add to dictionary successful?
   } // end addVertex

   public boolean addEdge(T begin, T end, double edgeWeight) {
       boolean result = false;

       VertexInterface<T> beginVertex = vertices.getValue(begin);
       VertexInterface<T> endVertex = vertices.getValue(end);

       if ((beginVertex != null) && (endVertex != null))
           result = beginVertex.connect(endVertex, edgeWeight);

       if (result)
           edgeCount++;

       return result;
   } // end addEdge

   public boolean addEdge(T begin, T end) {
       return addEdge(begin, end, 0);
   } // end addEdge

   public boolean hasEdge(T begin, T end) {
       boolean found = false;

       VertexInterface<T> beginVertex = vertices.getValue(begin);
       VertexInterface<T> endVertex = vertices.getValue(end);

       if ((beginVertex != null) && (endVertex != null)) {
           Iterator<VertexInterface<T>> neighbors = beginVertex
                   .getNeighborIterator();
           while (!found && neighbors.hasNext()) {
               VertexInterface<T> nextNeighbor = neighbors.next();
               if (endVertex.equals(nextNeighbor))
                   found = true;
           } // end while
       } // end if

       return found;
   } // end hasEdge

   public boolean isEmpty() {
       return vertices.isEmpty();
   } // end isEmpty

   public void clear() {
       vertices.clear();
       edgeCount = 0;
   } // end clear

   public int getNumberOfVertices() {
       return vertices.getSize();
   } // end getNumberOfVertices

   public int getNumberOfEdges() {
       return edgeCount;
   } // end getNumberOfEdges

   protected void resetVertices() {
       Iterator<VertexInterface<T>> vertexIterator = vertices
               .getValueIterator();
       while (vertexIterator.hasNext()) {
           VertexInterface<T> nextVertex = vertexIterator.next();
           nextVertex.unvisit();
           nextVertex.setCost(0);
           nextVertex.setPredecessor(null);
       } // end while
   } // end resetVertices

   public Queue<T> getBreadthFirstTraversal(T origin) {
       resetVertices();
       Queue<T> traversalOrder = new LinkedBlockingQueue<T>();
       Queue<VertexInterface<T>> vertexQueue = new LinkedBlockingQueue<VertexInterface<T>>();
       VertexInterface<T> originVertex = vertices.getValue(origin);
       originVertex.visit();
       traversalOrder.add(origin); // enqueue vertex label
       vertexQueue.add(originVertex); // enqueue vertex

       while (!vertexQueue.isEmpty()) {
           VertexInterface<T> frontVertex = vertexQueue.remove();

           Iterator<VertexInterface<T>> neighbors = frontVertex.getNeighborIterator();
           while (neighbors.hasNext()) {
               VertexInterface<T> nextNeighbor = neighbors.next();
               if (!nextNeighbor.isVisited()) {
                   nextNeighbor.visit();
                   traversalOrder.add(nextNeighbor.getLabel());
                   vertexQueue.add(nextNeighbor);
               } // end if
           } // end while
       } // end while

       return traversalOrder;
   } // end getBreadthFirstTraversal

   public Queue<T> getDepthFirstTraversal(T origin) {
       // assumes graph is not empty
       resetVertices();
       Queue<T> traversalOrder = new LinkedBlockingQueue<T>();
       Stack<VertexInterface<T>> vertexStack = new Stack<VertexInterface<T>>();

       VertexInterface<T> originVertex = vertices.getValue(origin);
       originVertex.visit();
       traversalOrder.add(origin); // enqueue vertex label
       vertexStack.push(originVertex); // enqueue vertex

       while (!vertexStack.isEmpty()) {
           VertexInterface<T> topVertex = vertexStack.peek();
           VertexInterface<T> nextNeighbor = topVertex.getUnvisitedNeighbor();

           if (nextNeighbor != null) {
               nextNeighbor.visit();
               traversalOrder.add(nextNeighbor.getLabel());
               vertexStack.push(nextNeighbor);
           } else
               // all neighbors are visited
               vertexStack.pop();
       } // end while

       return traversalOrder;
   } // end getDepthFirstTraversal

   public Stack<T> getTopologicalOrder() {
       resetVertices();

       Stack<T> vertexStack = new Stack<T>();
       int numberOfVertices = getNumberOfVertices();
       for (int counter = 1; counter <= numberOfVertices; counter++) {
           VertexInterface<T> nextVertex = findTerminal();
           nextVertex.visit();
           vertexStack.push(nextVertex.getLabel());
       } // end for

       return vertexStack;
   } // end getTopologicalOrder

  

  

   protected VertexInterface<T> findTerminal() {
       boolean found = false;
       VertexInterface<T> result = null;

       Iterator<VertexInterface<T>> vertexIterator = vertices
               .getValueIterator();

       while (!found && vertexIterator.hasNext()) {
           VertexInterface<T> nextVertex = vertexIterator.next();

           // if nextVertex is unvisited AND has only visited neighbors)
           if (!nextVertex.isVisited()) {
               if (nextVertex.getUnvisitedNeighbor() == null) {
                   found = true;
                   result = nextVertex;
               } // end if
           } // end if
       } // end while

       return result;
   } // end findTerminal

   // Used for testing
   public void display() {
       System.out.println("Graph has " + getNumberOfVertices()
               + " vertices and " + getNumberOfEdges() + " edges.");

       System.out.println(" Edges exist from the first vertex in each line to the other vertices in the line.");
       System.out.println("(Edge weights are given; weights are zero for unweighted graphs): ");
       Iterator<VertexInterface<T>> vertexIterator = vertices
               .getValueIterator();
       while (vertexIterator.hasNext()) {
           ((Vertex<T>) (vertexIterator.next())).display();
       } // end while
   } // end display

   private class EntryPQ implements Comparable<EntryPQ>, java.io.Serializable {
       private VertexInterface<T> vertex;
       private VertexInterface<T> previousVertex;
       private double cost; // cost to nextVertex

       private EntryPQ(VertexInterface<T> vertex, double cost,
               VertexInterface<T> previousVertex) {
           this.vertex = vertex;
           this.previousVertex = previousVertex;
           this.cost = cost;
       } // end constructor

       public VertexInterface<T> getVertex() {
           return vertex;
       } // end getVertex

       public VertexInterface<T> getPredecessor() {
           return previousVertex;
       } // end getPredecessor

       public double getCost() {
           return cost;
       } // end getCost

       public int compareTo(EntryPQ otherEntry) {
           // using opposite of reality since our priority queue uses a
           // maxHeap;
           // could revise using a minheap
           return (int) Math.signum(otherEntry.cost - cost);
       } // end compareTo

       public String toString() {
           return vertex.toString() + " " + cost;
       } // end toString
   } // end EntryPQ
} // end DirectedGraph

Explanation / Answer

Solution:

import java.util.Scanner;

import java.awt.*;

import java.applet.*;

import org.apache.jena.Graph2.* ;

import org.apache.jena.shared.AddDeniedException ;

import org.apache.jena.shared.ClosedException ;

import org.apache.jena.shared.DeleteDeniedException ;

import java.util.*;

import java.lang.*;

import java.io.*;

import java.util.ArrayList;

import org.apache.jena.shared.PrefixMapping ;

import org.apache.jena.shared.impl.PrefixMappingImpl ;

import org.apache.jena.util.iterator.ClosableIterator ;

import org.apache.jena.util.iterator.ExtendedIterator ;

public abstract class Graph2 implements Graph2WithPerform

{

protected boolean closed = false;

public Graph2() {}

protected void checkOpen()

{ if (closed) throw new ClosedException( "already closed", this ); }

@Override

public void close()

{

closed = true ;

}

@Override

public boolean isClosed()

{ return closed; }

@Override

public boolean dependsOn( Graph2 other )

{ return this == other; }

@Override

public Graph2StatisticsHandler getStatisticsHandler()

{

if (statisticsHandler == null) statisticsHandler = createStatisticsHandler();

return statisticsHandler;

}

protected Graph2StatisticsHandler statisticsHandler;

protected Graph2StatisticsHandler createStatisticsHandler()

{ return null; }

/**

Answer the event manager for this Graph2; allocate a new one if required.

Subclasses may override if they have a more specialised event handler.

The default is a SimpleEventManager.

*/

@Override

public Graph2EventManager getEventManager()

{

if (gem == null) gem = new SimpleEventManager( );

return gem;

}

/**

The event manager that this Graph2 uses to, well, manage events; allocated on

demand.

*/

protected Graph2EventManager gem;

/**

Tell the event manager that the triple <code>t</code> has been added to the Graph2.

*/

public void notifyAdd( Triple t )

{ getEventManager().notifyAddTriple( this, t ); }

/**

Tell the event manager that the triple <code>t</code> has been deleted from the

Graph2.

*/

public void notifyDelete( Triple t )

{ getEventManager().notifyDeleteTriple( this, t ); }

/**

Answer a transaction handler bound to this Graph2. The default is

SimpleTransactionHandler, which handles <i>no</i> transactions.

*/

@Override

public TransactionHandler getTransactionHandler()

{ return new SimpleTransactionHandler(); }

/**

Answer the capabilities of this Graph2; the default is an AllCapabilities object

(the same one each time, not that it matters - Capabilities should be

immutable).

*/

@Override

public Capabilities getCapabilities()

{

if (capabilities == null) capabilities = new AllCapabilities();

return capabilities;

}

/**

The allocated Capabilities object, or null if unallocated.

*/

protected Capabilities capabilities = null;

/**

Answer the PrefixMapping object for this Graph2, the same one each time.

*/

@Override

public PrefixMapping getPrefixMapping()

{

if ( pm == null )

pm = createPrefixMapping() ;

return pm;

}

protected PrefixMapping pm = null ;

protected PrefixMapping createPrefixMapping() { return new PrefixMappingImpl() ; }

@Override

public void add( Triple t )

{

checkOpen();

performAdd( t );

notifyAdd( t );

}

@Override

public void performAdd( Triple t )

{ throw new AddDeniedException( "Graph2::performAdd" ); }

@Override

public final void delete( Triple t )

{

checkOpen();

performDelete( t );

notifyDelete( t );

}

@Override

public void performDelete( Triple t )

{ throw new DeleteDeniedException( "Graph2::delete" ); }

/**

Remove all the statements from this Graph2.

*/

@Override

public void clear()

{

Graph2Util.remove(this, Node.ANY, Node.ANY, Node.ANY) ;

getEventManager().notifyEvent(this, Graph2Events.removeAll ) ;

}

/**

Remove all triples that match by find(s, p, o)

*/

@Override

public void remove( Node s, Node p, Node o )

{

Graph2Util.remove(this, s, p, o) ;

getEventManager().notifyEvent(this, Graph2Events.remove(s, p, o) ) ;

}

  

@Override

public final ExtendedIterator<Triple> find(Triple m)

{

checkOpen() ;

return Graph2Find(m) ;

}

protected abstract ExtendedIterator<Triple> Graph2Find( Triple triplePattern );

public ExtendedIterator<Triple> forTestingOnly_Graph2Find( Triple t )

{ return Graph2Find( t ); }

/**

  

*/

@Override

public final ExtendedIterator<Triple> find( Node s, Node p, Node o )

{ checkOpen();

return Graph2Find( s, p, o ); }

protected ExtendedIterator<Triple> Graph2Find( Node s, Node p, Node o )

{ return find( Triple.createMatch( s, p, o ) ); }

@Override

public final boolean contains( Triple t )

{ checkOpen();

return Graph2Contains( t ); }

/**

protected boolean Graph2Contains( Triple t )

{ return containsByFind( t ); }

@Override

public final boolean contains( Node s, Node p, Node o ) {

checkOpen();

return contains( Triple.create( s, p, o ) );

}

final protected boolean containsByFind( Triple t )

{

ClosableIterator<Triple> it = find( t );

try { return it.hasNext(); } finally { it.close(); }

}

@Override

public final int size()

{

checkOpen() ;

return Graph2Size() ;

}

protected int Graph2Size()

{

ExtendedIterator<Triple> it = Graph2Util.findAll( this );

try

{

int tripleCount = 0;

while (it.hasNext()) { it.next(); tripleCount += 1; }

return tripleCount;

}

finally

{ it.close(); }

}

@Override

public boolean isEmpty()

{ return size() == 0; }

public boolean isIsomorphicWith( Graph2 g )

{ checkOpen();

return g != null && Graph2Matcher.equals( this, g ); }

@Override public String toString()

{ return toString( (closed ? "closed " : ""), this ); }

public static final int TOSTRING_TRIPLE_BASE = 10;

public static final int TOSTRING_TRIPLE_LIMIT = 17;

  

public static String toString( String prefix, Graph2 that )

{

PrefixMapping pm = that.getPrefixMapping();

StringBuilder b = new StringBuilder( prefix + " {" );

int count = 0;

String gap = "";

ClosableIterator<Triple> it = Graph2Util.findAll( that );

while (it.hasNext() && count < TOSTRING_TRIPLE_LIMIT)

{

b.append( gap );

gap = "; ";

count += 1;

b.append( it.next().toString( pm ) );

}

if (it.hasNext()) b.append( "..." );

it.close();

b.append( "}" );

return b.toString();

}

}