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 +...
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity;...
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity; public Room() { this.capacity = 0; } /** * Constructor for objects of class Room * * @param rN the room number * @param bN the building name * @param c the room capacity */ public Room(String rN, String bN, int c) { setRoomNumber(rN); setBuildingName(bN); setCapacity(c); }    /** * Mutator method (setter) for room number. * * @param rN a new room number...
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...
package construction; public class Bid{ private String contractor; private float price; public Bid(String contractor, float price)...
package construction; public class Bid{ private String contractor; private float price; public Bid(String contractor, float price) { this.contractor = contractor; this.price = price; } public String getContractor() { return contractor; } public float getPrice() { return price; } } package construction; public class ContractorBids{ // assume proper variables and other methods are here public void winningBid(Bid[] bids, int numBids){ /**************************** * your code would go here * ****************************/ } } You are doing renovations on your building, and multiple contractors...
public class Person { private String name; public Person() { name = "No name yet"; }...
public class Person { private String name; public Person() { name = "No name yet"; } public Person(String initialName) { name = initialName; } public void setName(String newName) { name = newName; } public String getName() { return name; } public void writeOutput() { System.out.println("Name: " + name); } public boolean hasSameName(Person otherPerson) { return this.name.equalsIgnoreCase(otherPerson.name); } } 2- Write a Program Patient. Java Class that extends Person to include  Social security Gender  Appropriate construtors, accessors, and mutators....
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT