Advertisement
gelita

Graph directional

Feb 25th, 2020
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 17.76 KB | None | 0 0
  1. /**
  2.  *  
  3.  *
  4.  *  Problem: Graph
  5.  *
  6.  *  Prompt: Create a directed graph class using adjacency list edge
  7.  *          representation.
  8.  *
  9.  *  The Graph will have the following properties:
  10.  *
  11.  *             storage: {HashMap} - the keys represent unique vertex ids {Integer}
  12.  *                      and the values are Lists representing the
  13.  *                      vertex ids of its neighors.
  14.  *
  15.  *  The Graph will also have the following methods:
  16.  *
  17.  *           addVertex: Method that accepts a vertex id {Integer} and adds the
  18.  *                      vertex to the graph.  Return true if success and false
  19.  *                      if failed.
  20.  *
  21.  *                      Input:    id {Integer}
  22.  *                     Output:    {Boolean}
  23.  *
  24.  *        removeVertex: Method that accepts a vertex id and removes the vertex
  25.  *                      with the matching id. Return true if success and false
  26.  *                      if failed.
  27.  *
  28.  *                      Input:    id {Integer}
  29.  *                     Output:    {Boolean}
  30.  *
  31.  *             addEdge: Method that accepts two vertex ids and creates a
  32.  *                      directed edge from the first vertex to the second.
  33.  *                      Returns true if success and false if failed.
  34.  *
  35.  *                      Input:    id1 {Integer}
  36.  *                      Input:    id2 {Integer}
  37.  *                     Output:    {Boolean}
  38.  *
  39.  *          removeEdge: Method that accepts two vertex id's and removes the
  40.  *                      directed edge from the first vertex to the second.
  41.  *                      Returns true if success and false if failed.
  42.  *
  43.  *                       Input:    id1 {Integer}
  44.  *                       Input:    id2 {Integer}
  45.  *                      Output:    {Boolean}
  46.  *
  47.  *           isVertex:  Method that accepts an id, and returns whether the vertex
  48.  *                      exists in the graph.
  49.  *
  50.  *                       Input:    id {Integer}
  51.  *                      Output:   {Boolean}
  52.  *
  53.  *           neighbors: Method that accepts a vertex id, and returns all of the
  54.  *                      edges of that vertex.
  55.  *
  56.  *                       Input:    id {Integer}
  57.  *                     Output:   {List<Integer>}
  58.  *
  59.  *
  60.  *  Input:  {Void}
  61.  *  Output: {Graph}
  62.  *
  63.  *  Notes:   The notation for Time/Auxiliary Space Complexity for graphs
  64.  *           is slightly different since certain functions depend on
  65.  *           either the number of vertices, edges or even both
  66.  *
  67.  *           O(V) = Linear w/ respect to the number of vertices
  68.  *           O(E) = Linear w/ respect to the number of edges
  69.  *           O(V+E) = Linear w/ respect to the number of vertices * number of edges
  70.  */
  71.  
  72. import java.util.*;
  73.  
  74. class Graph {
  75.  
  76.   public Map<Integer, List<Integer>> storage = new HashMap<>();
  77.  
  78.   //   Time Complexity:
  79.   //   Auxiliary Space Complexity:
  80.   public boolean addVertex(Integer id) {
  81.       if(!storage.containsKey(id)){
  82.         storage.put(id, new LinkedList<Integer>());
  83.       }
  84.     return true;
  85.   }
  86.  
  87.   public boolean removeVertex(Integer id) {
  88.     storage.remove(id);
  89.     return true;
  90.   }
  91.  
  92.   //   Time Complexity:
  93.   //   Auxiliary Space Complexity:
  94.   public boolean addEdge(Integer id1, Integer id2) {
  95.     if(id1 == null  || id2 == null){
  96.       return false;
  97.     }
  98.     if(!storage.containsKey(id1)){
  99.       addVertex(id1);
  100.     }
  101.     if(!storage.containsKey(id2)){
  102.       addVertex(id2);
  103.     }
  104.     storage.get(id1).add(id2);
  105.     return true;
  106.   }
  107.  
  108.   // Time Complexity:
  109.   // Auxiliary Space Complexity:
  110. public boolean removeEdge(Integer id1, Integer id2) {
  111.     if (storage.containsKey(id1) && storage.containsKey(id2)) {
  112.       int index = storage.get(id1).indexOf(id2);
  113.       if (index >= 0) {
  114.         storage.get(id1).remove(index);
  115.         return true;
  116.       }
  117.     }
  118.     return false;
  119.   }
  120.  
  121.   //   Time Complexity:
  122.   //   Auxiliary Space Complexity:
  123.   public boolean isVertex(Integer id) {
  124.     return storage.containsKey(id);
  125.   }
  126.  
  127.   // Time Complexity:
  128.   // Auxiliary Space Complexity:
  129.   public List<Integer> neighbors(Integer id) {
  130.     if(storage.containsKey(id)){
  131.       return new ArrayList<Integer>(storage.get(id));
  132.     }
  133.     return null;
  134.   }
  135. }
  136.  
  137.  
  138. ////////////////////////////////////////////////////////////
  139. ///////////////  DO NOT TOUCH TEST BELOW!!!  ///////////////
  140. ////////////////////////////////////////////////////////////
  141.  
  142. // use the Main class to run the test cases
  143. class Main {
  144.   private int[] testCount;
  145.  
  146.   // an interface to perform tests
  147.   public interface Test {
  148.     public boolean execute();
  149.   }
  150.  
  151.   public static void main(String[] args) {
  152.  
  153.     int[] testCount = {0, 0};
  154.     System.out.println("Graph Class");
  155.  
  156.     assertTest(testCount, "able to create an instance", new Test() {
  157.       public boolean execute() {
  158.         Graph graph = new Graph();
  159.         return graph instanceof Graph;
  160.       }
  161.     });
  162.  
  163.     assertTest(testCount, "has storage field", new Test() {
  164.       public boolean execute() {
  165.         try {
  166.           Graph graph = new Graph();
  167.           graph.getClass().getDeclaredField("storage");
  168.           return true;
  169.         } catch (Exception e) {
  170.           e.printStackTrace();
  171.           return false;
  172.         }
  173.       }
  174.     });
  175.  
  176.     assertTest(testCount, "storage property initialized to a hash map", new Test() {
  177.       public boolean execute() {
  178.         try {
  179.           Graph graph = new Graph();
  180.           return graph.getClass().getDeclaredField("storage").getType().isAssignableFrom(Map.class) ||
  181.                  graph.getClass().getDeclaredField("storage").getType().isAssignableFrom(HashMap.class);
  182.         } catch (Exception e) {
  183.           e.printStackTrace();
  184.           return false;
  185.         }
  186.       }
  187.     });
  188.  
  189.     assertTest(testCount, "storage property initialized as empty", new Test() {
  190.       public boolean execute() {
  191.         try {
  192.           Graph graph = new Graph();
  193.           return graph.storage.size() == 0;
  194.         } catch (Exception e) {
  195.           e.printStackTrace();
  196.           return false;
  197.         }
  198.       }
  199.     });
  200.  
  201.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  202.  
  203.  
  204.     testCount[0] = 0;
  205.     testCount[1] = 0;
  206.     System.out.println("Graph addVertex method");
  207.  
  208.     assertTest(testCount, "has addVertex method", new Test() {
  209.       public boolean execute() {
  210.         try {
  211.           Graph graph = new Graph();
  212.           graph.getClass().getMethod("addVertex", new Class[] { Integer.class });
  213.           return true;
  214.         } catch (Exception e) {
  215.           e.printStackTrace();
  216.           return false;
  217.         }
  218.       }
  219.     });
  220.  
  221.     assertTest(testCount, "is able to add a vertex", new Test() {
  222.       public boolean execute() {
  223.         try {
  224.           Graph graph = new Graph();
  225.           graph.addVertex(5);
  226.           return graph.storage.size() == 1;
  227.         } catch (Exception e) {
  228.           e.printStackTrace();
  229.           return false;
  230.         }
  231.       }
  232.     });
  233.  
  234.     assertTest(testCount, "vertices store an list or set of connections", new Test() {
  235.       public boolean execute() {
  236.         try {
  237.           Graph graph = new Graph();
  238.           graph.addVertex(5);
  239.           return graph.storage.get(5) instanceof List ||
  240.                  graph.storage.get(5) instanceof ArrayList;
  241.         } catch (Exception e) {
  242.           e.printStackTrace();
  243.           return false;
  244.         }
  245.       }
  246.     });
  247.  
  248.     assertTest(testCount, "is able to add two vertices", new Test() {
  249.       public boolean execute() {
  250.         try {
  251.           Graph graph = new Graph();
  252.           graph.addVertex(5);
  253.           graph.addVertex(10);
  254.           return graph.storage.size() == 2 &&
  255.                  graph.storage.get(10) instanceof List ||
  256.                  graph.storage.get(10) instanceof ArrayList;
  257.         } catch (Exception e) {
  258.           e.printStackTrace();
  259.           return false;
  260.         }
  261.       }
  262.     });
  263.  
  264.     assertTest(testCount, "does not add in duplicate vertex", new Test() {
  265.       public boolean execute() {
  266.         try {
  267.           Graph graph = new Graph();
  268.           graph.addVertex(5);
  269.           graph.addVertex(5);
  270.           return graph.storage.size() == 1 && graph.storage.get(5).size() == 0;
  271.         } catch (Exception e) {
  272.           e.printStackTrace();
  273.           return false;
  274.         }
  275.       }
  276.     });
  277.  
  278.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  279.  
  280.  
  281.     testCount[0] = 0;
  282.     testCount[1] = 0;
  283.     System.out.println("Graph removeVertex method");
  284.  
  285.     assertTest(testCount, "has removeVertex method", new Test() {
  286.       public boolean execute() {
  287.         try {
  288.           Graph graph = new Graph();
  289.           graph.getClass().getMethod("removeVertex", new Class[] { Integer.class });
  290.           return true;
  291.         } catch (Exception e) {
  292.           e.printStackTrace();
  293.           return false;
  294.         }
  295.       }
  296.     });
  297.  
  298.     assertTest(testCount, "able to remove a vertex within graph", new Test() {
  299.       public boolean execute() {
  300.         Graph graph = new Graph();
  301.         graph.addVertex(5);
  302.         graph.removeVertex(5);
  303.         return graph.storage.size() == 0 && graph.storage.get(5) == null;
  304.       }
  305.     });
  306.  
  307.     assertTest(testCount, "does not remove vertex that does not exist", new Test() {
  308.       public boolean execute() {
  309.         Graph graph = new Graph();
  310.         graph.addVertex(5);
  311.         boolean result = graph.removeVertex(10);
  312.         return graph.storage.size() == 1 && graph.storage.get(5) != null;
  313.       }
  314.     });
  315.  
  316.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  317.  
  318.  
  319.     testCount[0] = 0;
  320.     testCount[1] = 0;
  321.     System.out.println("Graph addEdge method");
  322.  
  323.     assertTest(testCount, "has addEdge method", new Test() {
  324.       public boolean execute() {
  325.         try {
  326.           Graph graph = new Graph();
  327.           graph.getClass().getMethod("addEdge", new Class[] { Integer.class, Integer.class });
  328.           return true;
  329.         } catch (Exception e) {
  330.           e.printStackTrace();
  331.           return false;
  332.         }
  333.       }
  334.     });
  335.  
  336.     assertTest(testCount, "able to create an edge between two vertices that exist", new Test() {
  337.       public boolean execute() {
  338.         try {
  339.           Graph graph = new Graph();
  340.           graph.addVertex(5);
  341.           graph.addVertex(10);
  342.           graph.addEdge(5, 10);
  343.           return graph.storage.get(5).size() == 1 &&
  344.                  graph.storage.get(10).size() == 0;
  345.         } catch (Exception e) {
  346.           e.printStackTrace();
  347.           return false;
  348.         }
  349.       }
  350.     });
  351.  
  352.     assertTest(testCount, "addVertex returns true if vertices are added", new Test() {
  353.       public boolean execute() {
  354.         try {
  355.           Graph graph = new Graph();
  356.           graph.addVertex(5);
  357.           graph.addVertex(10);
  358.           return graph.addEdge(5, 10) == true;
  359.         } catch (Exception e) {
  360.           e.printStackTrace();
  361.           return false;
  362.         }
  363.       }
  364.     });
  365.  
  366.     assertTest(testCount, "does not create an edge when one of the vertices does not exist", new Test() {
  367.       public boolean execute() {
  368.         Graph graph = new Graph();
  369.         graph.addVertex(5);
  370.         boolean result = graph.addEdge(5, 10);
  371.         return graph.storage.get(5).size() == 0 && result == false;
  372.       }
  373.     });
  374.  
  375.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  376.  
  377.  
  378.     testCount[0] = 0;
  379.     testCount[1] = 0;
  380.     System.out.println("Graph removeEdge method");
  381.  
  382.     assertTest(testCount, "has removeEdge method", new Test() {
  383.       public boolean execute() {
  384.         try {
  385.           Graph graph = new Graph();
  386.           graph.getClass().getMethod("removeEdge", new Class[] { Integer.class, Integer.class });
  387.           return true;
  388.         } catch (Exception e) {
  389.           e.printStackTrace();
  390.           return false;
  391.         }
  392.       }
  393.     });
  394.  
  395.     assertTest(testCount, "able to remove an edge between two vertices", new Test() {
  396.       public boolean execute() {
  397.         try {
  398.           Graph graph = new Graph();
  399.           graph.addVertex(5);
  400.           graph.addVertex(10);
  401.           graph.addEdge(5, 10);
  402.           graph.removeEdge(5, 10);
  403.           return graph.storage.get(5).size() == 0 && graph.storage.size() == 2;
  404.         } catch (Exception e) {
  405.           e.printStackTrace();
  406.           return false;
  407.         }
  408.       }
  409.     });
  410.  
  411.     assertTest(testCount, "returns true if able to remove an edge", new Test() {
  412.       public boolean execute() {
  413.         try {
  414.           Graph graph = new Graph();
  415.           graph.addVertex(5);
  416.           graph.addVertex(10);
  417.           graph.addEdge(5, 10);
  418.           return graph.removeEdge(5, 10) == true;
  419.         } catch (Exception e) {
  420.           e.printStackTrace();
  421.           return false;
  422.         }
  423.       }
  424.     });
  425.  
  426.     assertTest(testCount, "does not remove edge when edge does not exist", new Test() {
  427.       public boolean execute() {
  428.         try{
  429.           Graph graph = new Graph();
  430.           graph.addVertex(5);
  431.           graph.addVertex(10);
  432.           graph.addEdge(5, 10);
  433.           graph.removeEdge(6, 10);
  434.           return graph.storage.get(5) != null && graph.storage.get(5).size() == 1;
  435.         } catch (Exception e) {
  436.           e.printStackTrace();
  437.           return false;
  438.         }
  439.       }
  440.     });
  441.  
  442.     assertTest(testCount, "returns false if edge does not exist", new Test() {
  443.       public boolean execute() {
  444.         try{
  445.           Graph graph = new Graph();
  446.           graph.addVertex(5);
  447.           graph.addVertex(10);
  448.           graph.addEdge(5, 10);
  449.           return graph.removeEdge(6, 10) == false;
  450.         } catch (Exception e) {
  451.           e.printStackTrace();
  452.           return false;
  453.         }
  454.       }
  455.     });
  456.  
  457.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  458.  
  459.  
  460.     testCount[0] = 0;
  461.     testCount[1] = 0;
  462.     System.out.println("Graph isVertex method");
  463.  
  464.     assertTest(testCount, "has isVertex method", new Test() {
  465.       public boolean execute() {
  466.         try {
  467.           Graph graph = new Graph();
  468.           graph.getClass().getMethod("isVertex", new Class[] { Integer.class });
  469.           return true;
  470.         } catch (Exception e) {
  471.           e.printStackTrace();
  472.           return false;
  473.         }
  474.       }
  475.     });
  476.  
  477.     assertTest(testCount, "returns true when a vertex exists", new Test() {
  478.       public boolean execute() {
  479.         try {
  480.           Graph graph = new Graph();
  481.           graph.addVertex(5);
  482.           graph.isVertex(5);
  483.           return graph.isVertex(5) == true;
  484.         } catch (Exception e) {
  485.           e.printStackTrace();
  486.           return false;
  487.         }
  488.       }
  489.     });
  490.  
  491.     assertTest(testCount, "returns false when a vertex does not exist'", new Test() {
  492.       public boolean execute() {
  493.         try {
  494.           Graph graph = new Graph();
  495.           graph.addVertex(5);
  496.           return graph.isVertex(10) == false;
  497.         } catch (Exception e) {
  498.           e.printStackTrace();
  499.           return false;
  500.         }
  501.       }
  502.     });
  503.  
  504.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  505.  
  506.  
  507.     testCount[0] = 0;
  508.     testCount[1] = 0;
  509.     System.out.println("Graph neighbors method");
  510.  
  511.     assertTest(testCount, "has neighbors method", new Test() {
  512.       public boolean execute() {
  513.         try {
  514.           Graph graph = new Graph();
  515.           graph.getClass().getMethod("neighbors", new Class[] { Integer.class });
  516.           return true;
  517.         } catch (Exception e) {
  518.           e.printStackTrace();
  519.           return false;
  520.         }
  521.       }
  522.     });
  523.  
  524.     assertTest(testCount, "returns null if the vertex does not exist", new Test() {
  525.       public boolean execute() {
  526.         try {
  527.           Graph graph = new Graph();
  528.           return graph.neighbors(5) == null;
  529.         } catch (Exception e) {
  530.           e.printStackTrace();
  531.           return false;
  532.         }
  533.       }
  534.     });
  535.  
  536.     assertTest(testCount, "returns an empty array if vertex has no edges", new Test() {
  537.       public boolean execute() {
  538.         try {
  539.           Graph graph = new Graph();
  540.           graph.addVertex(5);
  541.           return graph.neighbors(5).size() == 0;
  542.         } catch (Exception e) {
  543.           e.printStackTrace();
  544.           return false;
  545.         }
  546.       }
  547.     });
  548.  
  549.     assertTest(testCount, "returns neighbors if edges exist for a vertex", new Test() {
  550.       public boolean execute() {
  551.         try {
  552.           Graph graph = new Graph();
  553.           graph.addVertex(5);
  554.           graph.addVertex(10);
  555.           graph.addVertex(15);
  556.           graph.addVertex(20);
  557.           graph.addEdge(5, 10);
  558.           graph.addEdge(5, 15);
  559.           graph.addEdge(5, 20);
  560.           return graph.neighbors(5).size() == 3;
  561.         } catch (Exception e) {
  562.           e.printStackTrace();
  563.           return false;
  564.         }
  565.       }
  566.     });
  567.  
  568.     System.out.println("PASSED: " + testCount[0] + " / " + testCount[1] + "\n\n");
  569.   }
  570.  
  571.  
  572.   // function for checking if arrays contain same elements
  573.   // (do not need to be in the same order)
  574.   private static boolean arraysMatching(Integer[] arr1, Integer[] arr2) {
  575.     if (arr1.length != arr2.length) {
  576.       return false;
  577.     } else {
  578.       Arrays.sort(arr1);
  579.       Arrays.sort(arr2);
  580.  
  581.       for (int i = 0 ; i < arr1.length ; i++) {
  582.         if (arr1[i] != arr2[i]) {
  583.           return false;
  584.         }
  585.       }
  586.  
  587.       return true;
  588.     }
  589.   }
  590.  
  591.   // do not edit below, this is to wrap the test and check for exceptions
  592.   private static void assertTest(int[] count, String name, Test test) {
  593.     String pass = "false";
  594.     count[1]++;
  595.  
  596.     try {
  597.       if (test.execute()) {
  598.         pass = " true";
  599.         count[0]++;
  600.       }
  601.     } catch(Exception e) {}
  602.     String result = "  " + (count[1] + ")   ").substring(0, 5) + pass + " : " + name;
  603.     System.out.println(result);
  604.   }
  605. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement