Question

In: Computer Science

public class Graph { private ST<String, SET<String>> st; public Graph() { st = new ST<String, SET<String>>();...

public class Graph
{
   private ST<String, SET<String>> st;

   public Graph()
   {  st = new ST<String, SET<String>>();  }

   public void addEdge(String v, String w)
   {  // Put v in w's SET and w in v's SET.
      if (!st.contains(v)) st.put(v, new SET<String>());
      if (!st.contains(w)) st.put(w, new SET<String>());
      st.get(v).add(w);
      st.get(w).add(v);
   }

   public Iterable<String> adjacentTo(String v)
   {  return st.get(v);  }

   public Iterable<String> vertices()
   {  return st.keys();  }

   // See Exercises 4.5.1-4 for V(), E(), degree(),
   // hasVertex(), and hasEdge().

   public static void main(String[] args)
   {  // Read edges from standard input; print resulting graph.
      Graph G = new Graph();
      while (!StdIn.isEmpty())
         G.addEdge(StdIn.readString(), StdIn.readString());
      StdOut.print(G);
   }
}
  1. Modify the “Graph” program given in the textbook (program 4.5.1) to create a program, “SubGraph”. It would take a filename and vertices as input arguments on the command line. It would create and print out a graph using the data specified in the file (as is done by the "Graph" program). And then it would also print out the subgraph of the graph formed by the vertices that are given on the command line. [MO7.2]

Note: The induced subgraph is the graph comprised of the specified vertices together with all edges from the original graph that connect any two of them.

  • The input and output of the program should be similar to, or as specified by, the following sample run.

>more graph.txt
A B
A C
C G
A G
H A
B C
B H

>java SubGraph graph.txt A C G
The graph is
A: B C G H
B: A C H
C: A B G
G: A C
H: A B
The subgraph is
A: C G
C: A G
G: A C

Solutions

Expert Solution

Code:

package graph;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class SubGraph
{
   private ST<String, SET<String>> st;

   // number of edges
   private int E;

   public SubGraph()
   { st = new ST<String, SET<String>>(); }

   public SubGraph(String FileName)
   {
       st = new ST<String, SET<String>>();
       File file = new File(FileName);
       Scanner scanner = null;
       if (file.exists()) {
           FileInputStream fis = null;
       try {
           fis = new FileInputStream(file);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
           scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");
       }
       while (scanner.hasNextLine()) {
           String line = scanner.nextLine();
           String[] names = line.split(" ");
           for (int i = 1; i < names.length; i++) {
               addEdge(names[0], names[i]);
           }
       }
   }

   public void addEdge(String v, String w)
   { // Put v in w's SET and w in v's SET.
      if (!st.contains(v)) st.put(v, new SET<String>());
      if (!st.contains(w)) st.put(w, new SET<String>());
      st.get(v).add(w);
      st.get(w).add(v);
   }

   public boolean hasEdge(String v, String w) {
       return st.get(v).contains(w);
   }


   public String toString() {
       StringBuilder s = new StringBuilder();
       for (String v : st) {
           s.append(v + ": ");
           for (String w : st.get(v)) {
               s.append(w + " ");
           }
           s.append('\n');
       }
       return s.toString();
   }

   public Iterable<String> adjacentTo(String v)
   { return st.get(v); }

   public Iterable<String> vertices()
   { return st.keys(); }


   public static void main(String[] args)
   {
      SubGraph G = new SubGraph(args[0]);
      System.out.println("The graph is");
      System.out.println(G.toString());
    
      SubGraph SG = new SubGraph();
    
      for(int i = 1;i < args.length; i++)
      {
          for(int j = 1; j< args.length;j++)
              if(G.hasEdge(args[i], args[j]))
                  SG.addEdge(args[i], args[j]);
      }
    
      System.out.println("\nThe subgraph is");
      System.out.println(SG.toString());
   }
}

CommandLine Arguments:

graph.txt A C G

Output:

The graph is
A: B C G H
B: A C H
C: A B G
G: A C
H: A B

The subgraph is
A: C G
C: A G
G: A C

Note:

1. Place the file 'graph.txt' in the working directory.


Related Solutions

public class StringNode { private String item; private StringNode next; } public class StringLL { private...
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } } In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 =...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 = new HashSet<String>();    for (String temp : set) {        temp = temp.replaceAll(        "[^0-9]", "");                  if(!(set.isEmpty())){            set2.add(temp);        }    }    return set2;               } public static void main(String args[]) { // create empty set Set<String> set = new HashSet<String>(); // {3, 25, 33, 21, 55, 43, 78,...
package mac286.LinkedLists; public class Postfix { private rStack<String> S; private String inSt; private ourLinkedList<String> inList, outList;...
package mac286.LinkedLists; public class Postfix { private rStack<String> S; private String inSt; private ourLinkedList<String> inList, outList; public Postfix(String s) { S = new rStack<String>(); inSt = s; outList = new ourLinkedList<String>(); inList = new ourLinkedList<String>(); } public void reset(String s) { S = new rStack<String>(); inSt = s; outList = new ourLinkedList<String>(); inList = new ourLinkedList<String>(); } private boolean isOperator(char c) { if(c=='-'||c=='+'||c=='*'||c=='/') return true; return false; } private boolean isParenthesis(char c) { if(c == '(' || c==')') return true;...
package compstore; public class Desktop{ private String brand; private float price; public Desktop(String brand, float price)...
package compstore; public class Desktop{ private String brand; private float price; public Desktop(String brand, float price) { this.brand = brand; this.price = price; } public String getBrand() { return brand; } public float getPrice() { return price; } } package compstore; public class DeskTopDeals{ // assume proper variables and other methods are here public void dealOfTheDay(Desktop[] items, int numItems){ /**************************** * your code would go here * ****************************/ } } Given the above Desktop class, write code that should go...
Suppose we have a Java class called Person.java public class Person { private String name; private...
Suppose we have a Java class called Person.java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName(){return name;} public int getAge(){return age;} } (a) In the following main method which lines contain reflection calls? import java.lang.reflect.Field; public class TestPerson { public static void main(String args[]) throws Exception { Person person = new Person("Peter", 20); Field field = person.getClass().getDeclaredField("name"); field.setAccessible(true); field.set(person, "Paul"); } }...
java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a...
java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a bank account with a zero balance @param accountID - ID of the Account */ public BankAccount(String accountID) { balance = 0; this.accountID = accountID; } /** Constructs a bank account with a given balance @param initialBalance the initial balance @param accountID - ID of the Account */ public BankAccount(double initialBalance, String accountID) { this.accountID = accountID; balance = initialBalance; } /** * Returns the...
// Base class for game configuration public abstract class DataSource {     private Graph map;    ...
// Base class for game configuration public abstract class DataSource {     private Graph map;     private HashMap <String,Room> rooms;     private ArrayList <Entity> entities;     private Player player;     protected HashMap < String, List<String[]> > tables;     // constructor     public DataSource() {     }         // Connect to the data source. Override if source is a database     public void connect() {     };         // Load the configuration tables required to build the game world...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:   ...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:    Tune();    Tune( const string &n );      const string & get_title() const; }; class Music_collection { private: int number; // the number of tunes actually in the collection int max; // the number of tunes the collection will ever be able to hold Tune *collection; // a dynamic array of Tunes: "Music_collection has-many Tunes" public: // default value of max is a conservative...
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT