Question

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

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import org.apache.jena.Graph2.* ;

import org.apache.jena.shared.AddDeniedException ;

import org.apache.jena.shared.ClosedException ;

import org.apache.jena.shared.DeleteDeniedException ;

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();

          }

}

Add a comment
Know the answer?
Add Answer to:
Please try your best to complete this 11 methods under. I have provided the UndirectedGraph class...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void...

    Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void main(String[] args) { int currentVertex, userChoice; Scanner input = new Scanner(System.in); // create graph using your WeightedGraph based on author's Graph WeightedGraph myGraph = new WeightedGraph(4); // add labels myGraph.setLabel(0,"Spot zero"); myGraph.setLabel(1,"Spot one"); myGraph.setLabel(2,"Spot two"); myGraph.setLabel(3,"Spot three"); // Add each edge (this directed Graph has 5 edges, // so we add 5 edges) myGraph.addEdge(0,2,9); myGraph.addEdge(1,0,7); myGraph.addEdge(2,3,12); myGraph.addEdge(3,0,15); myGraph.addEdge(3,1,6); // let's pretend we are on...

  • It's important project. I need a help. Will give up vote for helping! Please use Java !!!!! Need ...

    It's important project. I need a help. Will give up vote for helping! Please use Java !!!!! Need clearly written java program code and sample output!!!!!! The popular social network Facebook TM was founded by Mark Zuckerberg and his classmates at Harvard University in 2004. At the time, he was a sophomore studying computer science. Design and implement an application that maintains the data for a simple social network. Each person in the network should have a profile that contains...

  • Please follow all the instructions and do all the parts (a-d)! Create a Java program which implem...

    Please follow all the instructions and do all the parts (a-d)! Create a Java program which implements Dijkstra’s shortest path algorithm according to the psueudocode below. Base the design on the weighted graph implementation used in Problem3.java (provided at the bottom). Your program should include the following features: a. A new method receives a starting vertex index and a target vertex index (e.g. 0 and 4). It computes the shortest distances to all vertexes using Dijkstra’s algorithm. The pseudocode is...

  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements...

    Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements DictionaryInterface<K, V> { private int numEntries; private static final int DEFAULT_CAPACITY = 5; private static final int MAX_CAPACITY = 10000; private TableEntry<K, V>[] table; private double loadFactor; private static final double DEFAULT_LOAD_FACTOR = 0.75; public HashTableOpenAddressing() { this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashTableOpenAddressing(int initialCapacity, double loadFactorIn) { numEntries = 0; if (loadFactorIn <= 0 || initialCapacity <= 0) { throw new IllegalArgumentException("Initial capacity and load...

  • I am unsure how to add the following methods onto this code?? please help - rowValuesIncrease(int[][]...

    I am unsure how to add the following methods onto this code?? please help - rowValuesIncrease(int[][] t) A method that returns true if from left to right in any row, the integers are increasing, otherwise false. - columnValuesIncrease(int[][] t) A method that returns true if from top to bottom in any column, the integers are increasing, otherwise false. - isSetOf1toN(int[][] t) A method that returns true if the set of integers used is {1, 2, . . . , n}...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT