Guest User

Untitled

a guest
Apr 10th, 2017
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 35.31 KB | None | 0 0
  1.  
  2. public interface Graph<E> {
  3.     //OVERVIEW: The data type Graph<E> represents a set of homogeneous items
  4.     //          each element has type E, and they are organized using an undirected graph structure
  5.     //TYPICAL ELEMENT:  G = (V, E), where V contains the vertexes and E contains the edges in G
  6.     //                              and each edge is an unordered pair in VxV
  7.     //                  V = {vertex_1, ... , vertex_n}
  8.     //                  E = {{x1; y1}, ... , {x_m; y_m}}
  9.    
  10.     /* If elem isn't already a vertex in this, it adds the given vertex to the set V and returns true, it returns false otherwise */
  11.     public boolean addNode(E elem) throws NullPointerException;
  12.     //MODIFIES: V
  13.     //EFFECTS:  If V doesn't contain elem, it adds elem to V and returns true,
  14.     //          it returns false without modifying this otherwise.
  15.     //          if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
  16.    
  17.     /* If {x; y} isn't already an existing edge in this, and x and y are both already existing vertexes in this, it adds {x; y} to the set E and returns true, it returns false otherwise */
  18.     public boolean addEdge(E x, E y) throws NullPointerException, IllegalArgumentException;
  19.     //MODIFIES: E
  20.     //EFFECTS:  If E doesn't contain {x; y} and both x and y are contained in V, it adds {x; y} to E and returns true,
  21.     //          it returns false without modifying this if E already contains {x; y}.
  22.     //          if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
  23.     //          if either x or y aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
  24.    
  25.     /* If elem is a vertex in this, it removes elem from this, along with every edge incident on elem and returns true, it returns false otherwise */
  26.     public boolean removeNode(E elem) throws NullPointerException;
  27.     //MODIFIES: V, E
  28.     //EFFECTS:  If V contains elem, it removes elem from V, proceeds to remove from E each edge which is incident on elem, and then returns true,
  29.     //          it returns false without modifying this otherwise.
  30.     //          if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
  31.    
  32.     /* If {x; y} is an existing edge in this, it removes {x; y} from the set E and returns true, it returns false otherwise */
  33.     public boolean removeEdge(E x, E y) throws NullPointerException, IllegalArgumentException;
  34.     //MODIFIES: E
  35.     //EFFECTS:  If E contains {x; y}, it removes {x; y} from E and returns true,
  36.     //          it returns false without modifying this otherwise.
  37.     //          if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
  38.     //          if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
  39.    
  40. }
  41.  
  42. import java.util.*;
  43.  
  44. public class MyGraph<E> implements Graph<E> {
  45.     //OVERVIEW: A set of homogeneous items each with type E,
  46.     //          organized using an undirected graph structure
  47.    
  48.     //AF(c):=   G = (V, E) where
  49.     //          V = {c._values.get(i) | 0 <= i < c._nodeCount }
  50.     //          E = {{c._values.get(i); c._values.get(c._adj.get(i).get(j))} | (0 <= i < c._nodeCount) && (0 <= j < c._adj.get(i).size())}
  51.    
  52.     //RI(c):=   c._values != null && c._adj != null && (c._adj.get(i) != null) for each 0 <= i < c._nodeCount
  53.     //      &&  c._values.size() == c._adj.size() == c._nodeCount && c._nodeCount >= 0
  54.     //      &&  c._values.get(i) != null for each 0 <= i < c._nodeCount && for each i such that 0 <= i < c._nodeCount ==> c._adj.get(i).size() <= c._nodeCount
  55.     //      &&  c._adj.get(i).get(j) != null for each (i, j) such that (0 <= i < c._nodeCount) && (0 <= j < c._adj.get(i).size())
  56.     //      &&  for each (i, j) such that 0 <= i < j < c._nodeCount ==> c._values.get(i) != c._values.get(j)
  57.     //      &&  for each (k, i, j) such that ((0 <= k < c._nodeCount) && (0 <= i < j < c._adj(k).size())) ==> c._adj.get(k).get(i) != c._adj.get(k).get(j)
  58.     //      &&  for each (i, j) such that (0 <= i < c._nodeCount && 0 <= j < c._adj.get(i).size()) ==> 0 <= c._adj.get(i).get(j) < c._nodeCount
  59.     //      &&  for each (i, j) such that (0 <= i < c._nodeCount && 0 <= j < c._adj.get(i).size()) ==> there is one h such that
  60.     //              (0 <= h < c._adj.get(c._adj.get(i).get(j)).size()) && h == i
  61.        
  62.     private Vector<E> _values;
  63.     private Vector<Vector<Integer>> _adj;
  64.     private Integer _nodeCount;
  65.    
  66.     /* Instantiates this to an empty graph (a graph where both E and V have no elements) */
  67.     public MyGraph() {
  68.         //MODIFIES: _values, _adj, _nodeCount
  69.         //EFFECTS:  Sets both _values and _adj to empty lists and _nodeCount to 0 representing an empty graph
  70.        
  71.         _values = new Vector<E>();
  72.         _adj = new Vector<Vector<Integer>>();
  73.         _nodeCount = 0;
  74.     }
  75.    
  76.     /* If elem isn't already a vertex in this, it adds the given vertex to the set V and returns true, it returns false otherwise */
  77.     public boolean addNode(E elem) throws NullPointerException {
  78.         //MODIFIES: _values, _adj, _nodeCount
  79.         //EFFECTS:  if _values doesn't contains elem, it adds elem to it, adds a new empty list to _adj containing the vertexes adjacent to elem,
  80.         //              it increments _nodeCount and returns true. It returns false without modifying this otherwise.
  81.         //          if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
  82.        
  83.         if (elem == null) throw new NullPointerException();
  84.        
  85.         if (_values.indexOf(elem) < 0) {
  86.             _values.add(elem);
  87.             _nodeCount++;
  88.             _adj.add(new Vector<Integer>());
  89.            
  90.             return true;
  91.         }
  92.         return false;
  93.     }
  94.  
  95.     /* If {x; y} isn't already an existing edge in this, and x and y are both already existing vertexes in this, it adds {x; y} to the set E and returns true, it returns false otherwise */
  96.     public boolean addEdge(E x, E y) throws NullPointerException, IllegalArgumentException {
  97.         //MODIFIES: _adj
  98.         //EFFECTS:  if (x, y) already has a corresponding node in this, it returns false without modifying this, if not
  99.         //          it adds y to the list of vertexes adjacent to x and vice versa
  100.         //          if x equals y, it skips adding a duplicate adjacent vertex
  101.         //          if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
  102.         //          if either x or y aren't already contained in _values, it throws an IllegalArgumentException (default exception in Java, unchecked).
  103.        
  104.         if (x == null || y == null) throw new NullPointerException();
  105.         if (!(_values.contains(x) && _values.contains(y))) throw new IllegalArgumentException();
  106.        
  107.         int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
  108.        
  109.         Vector<Integer> adj_x = _adj.get(ind_x);
  110.         if (adj_x.indexOf(ind_y) >= 0) return false;
  111.        
  112.         adj_x.add(ind_y);
  113.         if (ind_x != ind_y) //this avoids the duplicate edge in case the user is adding a {x, x} edge
  114.             _adj.get(ind_y).add(ind_x);
  115.        
  116.         return true;
  117.     }
  118.  
  119.     /* If elem is a vertex in this, it removes elem from this, along with every edge incident on elem and returns true, it returns false otherwise */
  120.     public boolean removeNode(E elem) throws NullPointerException {
  121.         //MODIFIES: _values, _adj, _nodeCount
  122.         //EFFECTS:  if _values doesn't contain elem, it returns false without modifying this,
  123.         //          otherwise, it proceeds by removing elem from each list of adjacent nodes, then, it removes elem from _values and it's corresponding list of adjacent vertexes
  124.         //          if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
  125.        
  126.         if (elem == null) throw new NullPointerException();
  127.        
  128.         int index = _values.indexOf(elem);
  129.         if (index < 0) return false;
  130.        
  131.         for(Integer el : _adj.get(index))
  132.             if (el != index) _adj.get(el).removeElement(index);
  133.        
  134.         _adj.remove(index);
  135.         _values.remove(index);
  136.         _nodeCount--;
  137.        
  138.         return true;
  139.     }
  140.  
  141.     /* If {x; y} is an existing edge in this, it removes {x; y} from the set E and returns true, it returns false otherwise */
  142.     public boolean removeEdge(E x, E y) throws NullPointerException,  IllegalArgumentException {
  143.         //MODIFIES: _adj
  144.         //EFFECTS:  if (x, y) doesn't have a corresponding edge in this, it returns false without modifying this,
  145.         //          otherwise, it proceeds by removing x from the list of y's adjacent nodes, and vice versa.
  146.         //          if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
  147.         //          if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
  148.        
  149.         if (x == null || y == null) throw new NullPointerException();
  150.         int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
  151.         if (ind_x < 0 || ind_y < 0) throw new IllegalArgumentException();
  152.        
  153.         if (!_adj.get(ind_x).contains(ind_y)) return false;
  154.        
  155.         _adj.get(ind_x).removeElement(ind_y);
  156.         if (ind_x != ind_y) //if x == y, there is only one adjacent representation to be removed
  157.             _adj.get(ind_y).remove(ind_x);
  158.                
  159.         return true;
  160.     }
  161.    
  162.     /* If both src and dst are nodes in this, it returns the distance between src and dst, returning -1 if those aren't connected*/
  163.     public int distance(E src, E dst) throws NullPointerException, IllegalArgumentException {
  164.         //MODIFIES: none
  165.         //EFFECTS:  it returns the distance between src and dst (the length of the shortest path from src to dst)
  166.         //          if src and dst aren't connected it returns -1
  167.         //          if either src or dst equals null, it throws a NullPointerException (default exception in Java, unchecked),
  168.         //          if either src or dst aren't already contained in _values, it throws an IllegalArgumentException (default exception in Java, unchecked).
  169.        
  170.         if (src == null || dst == null) throw new NullPointerException();
  171.         if (!(_values.contains(src) && _values.contains(dst))) throw new IllegalArgumentException();
  172.        
  173.         return bfs_getDistance(_values.indexOf(src))[_values.indexOf(dst)];
  174.     }
  175.    
  176.     /* It returns the diameter of this, which is the longest distance between two nodes in this, it returns -1 if there are no nodes in this*/
  177.     public int diameter() {
  178.         //MODIFIES: none
  179.         //EFFECTS:  It returns the diameter of this, calculated by comparing the distance between every pair of nodes
  180.         //          it returns -1 if _values is empty
  181.        
  182.         int _max = -1;
  183.         int[] el_dist;
  184.         for (int i = 0; i < _nodeCount; i++) {
  185.             el_dist = bfs_getDistance(i);
  186.             for (int x : el_dist)
  187.                 if (x > _max) _max = x;
  188.         }
  189.        
  190.         return _max;
  191.     }
  192.    
  193.     /* It returns cardinality of the set V in this*/
  194.     public int nodeCount() {
  195.         //MODIFIES: none
  196.         //EFFECTS:  It returns the value of this._nodeCount
  197.        
  198.         return _nodeCount;
  199.     }
  200.    
  201.     /* It returns true if x is a node in this, false otherwise*/
  202.     public boolean containsNode(E x) {
  203.         //MODIFIES: none
  204.         //EFFECTS:  It returns true if _values contains x, false otherwise
  205.         //          if x equals null, it throws a NullPointerException (default exception in Java, unchecked).
  206.        
  207.         if (x == null) throw new NullPointerException();
  208.        
  209.         return _values.contains(x);
  210.     }
  211.    
  212.     /* It returns true if {x; y} is an edge in this, false otherwise*/
  213.     public boolean containsEdge(E x, E y) {
  214.         //MODIFIES: none
  215.         //EFFECTS:  It returns true if this contains the edge {x; y}, false otherwise
  216.         //          if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
  217.         //          if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
  218.        
  219.         if (x == null || y == null) throw new NullPointerException();
  220.         int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
  221.         if (ind_x < 0 || ind_y < 0) throw new IllegalArgumentException();
  222.        
  223.         return _adj.get(ind_x).contains(ind_y);
  224.     }
  225.    
  226.     /* It returns a list containing the String representation of each node adjacent to x in this*/
  227.     public Vector<String> getAdjacents (E x) {
  228.         //MODIFIES: none
  229.         //EFFECTS:  It returns a new Vector<String> containing the String representation of each node in this which is adjacent to x
  230.         //          if x equals null, it throws a NullPointerException (default exception in Java, unchecked),
  231.         //          if x isn't contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
  232.                
  233.         if (x == null) throw new NullPointerException();
  234.         int ind_x;
  235.         if ((ind_x = _values.indexOf(x)) < 0) throw new IllegalArgumentException();
  236.        
  237.         Vector<String> _out = new Vector<String>();
  238.         for (Integer a : _adj.get(ind_x)) _out.add(_values.get(a).toString());
  239.        
  240.         return _out;
  241.     }
  242.    
  243.     /* It returns a String representation of the sets V and E in this*/
  244.     public String toString(){
  245.         //MODIFIES: none
  246.         //EFFECTS:  It returns a String containing a visualization of the vertexes and edges in this
  247.        
  248.         String v = "V = {", e = "E = {";
  249.         for (E el : _values) v += el.toString() + "; ";
  250.         for (int i = 0; i < _nodeCount; i++)
  251.             for(Integer el : _adj.get(i))
  252.                 if (el >= i) e += "{" + _values.get(i).toString() + "; " + _values.get(el).toString() + "} ";
  253.         return v + "}\n" + e + "}";
  254.     }
  255.    
  256.     /* It returns true if this and g represent the same graph, false otherwise*/
  257.     @SuppressWarnings("unchecked")
  258.     public boolean equals(Object g) {
  259.         //MODIFIES: none
  260.         //EFFECTS:  It returns true if this and g represent the same graph, false otherwise,
  261.         //          if e equals null, it throws a NullPointerException (default exception in Java, unchecked.
  262.        
  263.         if (g == null) return false;
  264.         MyGraph<E> conv;
  265.         int index;
  266.        
  267.         try {
  268.             conv = (MyGraph<E>)g;
  269.         }
  270.         catch (ClassCastException exc)  {   return false;   }
  271.        
  272.         if (_nodeCount != conv._nodeCount) return false;
  273.        
  274.         for (int i = 0; i < _nodeCount; i++) {
  275.             index = conv._values.indexOf(_values.get(i));
  276.             if (index < 0) return false;
  277.             for (Integer ref : _adj.get(i))
  278.                 if (!conv._adj.get(index).contains(ref)) return false;
  279.         }
  280.        
  281.         return true;
  282.     }
  283.    
  284.     // Private/ Protected methods below:
  285.    
  286.     /* Esegue una BFS su this partendo dal nodo di indice source e restituisce le distanze da essa in un array*/
  287.     private int[] bfs_getDistance(int source) {
  288.         LinkedList<Integer> queue = new LinkedList<Integer>();
  289.         Integer el = source;
  290.         int[] status = new int[_values.size()], _distance = new int[_values.size()];
  291.         //0 = non_visitato;
  292.         //1 = in_visita
  293.         //2 = visitato
  294.        
  295.         for (int i = 0; i < _values.size(); i++)
  296.             _distance[i] = -1;
  297.        
  298.         queue.add(source);
  299.         _distance[source] = 0;
  300.         status[source] = 1;
  301.        
  302.         do
  303.         {
  304.             for (Integer x : _adj.get(el))
  305.                 if (status[x] == 0) {
  306.                     status[x] = 1;  //marco ogni adiacente come in visita
  307.                     _distance[x] = _distance[el] + 1;
  308.                     queue.addLast(x);
  309.                 }
  310.            
  311.             status[el] = 2; //marco el come visitato
  312.            
  313.             try {
  314.                 el = queue.removeFirst();
  315.             } catch (NoSuchElementException e) { el = -1; }
  316.         } while (el != -1);
  317.        
  318.         return _distance;
  319.        
  320.     }
  321. }
  322.  
  323.  
  324. public class UserAccount {
  325.     //OVERVIEW: The type UserAccount represents a set of values associated to some parameters which identify a person's account.
  326.     //TYPICAL ELEMENT:  P (P being a person's profile) where:
  327.     //                      P.FirstName     := The first name of P's owner
  328.     //                      P.LastName      := The last name of P's owner
  329.     //                      P.Email         := The email which P's owner used in P
  330.    
  331.     //AF(c):=   P   where:
  332.     //              P.FirstName = c._name
  333.     //              P.LastName  = c._surname
  334.     //              P.Email     = c._email
  335.    
  336.     //RI(c):=   c._name != null && c._surname != null && c._email != null
  337.     //      &&  c._name.length() <= 20 && c._surname.length() <= 20
  338.    
  339.     private String _name, _surname, _email;
  340.    
  341.     /* Instantiates this to a new UserAccount (setting every value to given parameters) */
  342.     public UserAccount(String name, String surname, String email) {
  343.         //MODIFIES: _name, _surname, _email
  344.         //EFFECTS:  Sets _name, _surname and _email to given parameters
  345.         //          if either name, surname or email equals null, it throws a NullPointerException (default exception in Java, unchecked),
  346.         //          if either name or surname has a length > 20, it throws an IllegalArgumentException (default exception in Java, unchecked).
  347.        
  348.         if (name == null || surname == null || email == null) throw new NullPointerException();
  349.         if (name.length() > 20 || surname.length() > 20) throw new IllegalArgumentException("Name / Surname too long");
  350.         _name = name;
  351.         _surname = surname;
  352.         _email = email;
  353.     }
  354.    
  355.     /* Instantiates this to a new UserAccount (copying each value from a given UserAccount) */
  356.     public UserAccount(UserAccount a) {
  357.         //MODIFIES: _name, _surname, _email
  358.         //EFFECTS:  Sets _name, _surname and _email to a._name, a._surname and a._email respectively
  359.         //          if a equals null, it throws a NullPointerException (default exception in Java, unchecked).
  360.        
  361.         if (a == null) throw new NullPointerException();
  362.         _name = a._name;
  363.         _surname = a._surname;
  364.         _email = a._email;
  365.     }
  366.  
  367.     /* Returns the first name value in this */
  368.     public String getName() {
  369.         //MODIFIES: none
  370.         //EFFECTS:  Returns this._name
  371.                
  372.         return _name;
  373.     }
  374.    
  375.     /* Returns the last name value in this */
  376.     public String getSurame() {
  377.         //MODIFIES: none
  378.         //EFFECTS:  Returns this._surname
  379.        
  380.         return _surname;
  381.     }
  382.    
  383.     /* Returns the email value in this */
  384.     public String getEmail() {
  385.         //MODIFIES: none
  386.         //EFFECTS:  Returns this._email
  387.        
  388.         return _email;
  389.     }
  390.    
  391.     /* It returns true if this and a have the same email value, false otherwise */
  392.     public boolean sameEmail(UserAccount a){
  393.         //MODIFIES: none
  394.         //EFFECTS:  It returns true if this._email equals a._email, false otherwise.
  395.        
  396.         if (a == null) throw new NullPointerException();
  397.        
  398.         return _email.equals(a._email);
  399.     }
  400.    
  401.     /* It returns a String representation of this*/
  402.     public String toString() {
  403.         //MODIFIES: none
  404.         //EFFECTS:  It returns a String containing a visualization of _name, _surname and _email from this
  405.        
  406.         return _surname + ", " + _name + " | " + _email;
  407.     }
  408.    
  409.     /* It returns true if this and e represent the same UserAccount, false otherwise*/
  410.     public boolean equals(Object e) {
  411.         //MODIFIES: none
  412.         //EFFECTS:  It returns true if e can be converted to a UserAccount value and has each value equal to this, false otherwise
  413.         //          if e equals null, it throws a NullPointerException (default exception in Java, unchecked.
  414.                
  415.         if (e == null) return false;
  416.        
  417.         try {
  418.             UserAccount conv = (UserAccount)e;
  419.             return _email.equals(conv._email)
  420.                     && _name.equals(conv._name)
  421.                     && _surname.equals(conv._surname);
  422.         }
  423.         catch (ClassCastException exc)  {   return false;   }
  424.        
  425.     }
  426. }
  427.  
  428. import java.util.Hashtable;
  429. import java.util.Vector;
  430.  
  431. public class SocialNetwork {
  432.     //OVERVIEW: The type SocialNetwork represents a set of UserAccounts organized in an undirected graph structure, where each edge represents a friendship relation.
  433.     //              It is based on a Facebook-like structure, where a friendship relation is mutual
  434.     //TYPICAL ELEMENT:  S = (A, R), where A contains the user's accounts and R contains the relations represented by the edges of the graph
  435.     //                  A = {<user_1, data_1>, ... , <user_n, data_n>}      where each item in A is a pair composed of a username (String) and a UserAccount object
  436.     //                  E = {{x1; y1}, ... , {x_m; y_m}}        where each edge is a set composed of two usernames contained in A
  437.    
  438.     //AF(c):=   S = (A, R) where
  439.     //          A = {<k, c._users.get(k)> | for each key k in c._users.keySet() }
  440.     //          R = c._relations.E      as friendship relations are directly implemented as the set of edges in the MyGraph parameter _relations
  441.    
  442.     //RI(c):=   c._users != null && c._relations != null
  443.     //      &&  c._users.size() == c._relations.nodeCount()
  444.     //      &&  for each key k in c._users.keySet() ==> k != null && c._users.get(k) != null && k.length() < 16
  445.     //      &&  for each pair of keys (k, h) in (c._users.keySet() x c._users.keySet()) ==> c._users.get(k).sameEmail(c._users.get(h)) == false
  446.     //      &&  for each key k in c._users.keySet() ==> c._relations.containsNode(k) == true
  447.     //      &&  for each node n in c._relations.V ==> c._users.keySet().contains(n) == true
  448.    
  449.     private Hashtable<String, UserAccount> _users;
  450.     private MyGraph<String> _relations;
  451.    
  452.     /* Instantiates this to a new empty SocialNetwork (containing no account and no relations) */
  453.     public SocialNetwork(){
  454.         //MODIFIES: _users, _relations
  455.         //EFFECTS:  Sets _users and _relations to an empty Hashtable and an empty MyGraph respectively
  456.                
  457.         _users = new Hashtable<String, UserAccount>();
  458.         _relations = new MyGraph<String>();
  459.     }
  460.    
  461.     /* Adds the pair <user, a> to this.A */
  462.     public void addAccount(String user, UserAccount a) {
  463.         //MODIFIES: _users, _relations
  464.         //EFFECTS:  Maps the key user to the UserAccount a in this._users and adds user as a new node to _relations
  465.         //          if either user or a equals null, it throws a NullPointerException (default exception in Java, unchecked),
  466.         //          if user is a key already existing in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
  467.         //          if a is already mapped in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
  468.         //          if a shares it's email with an existing value in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
  469.         //          if user's length is more or equal to 16, it throws an IllegalArgumentException (default exception in Java, unchecked).
  470.        
  471.         if (user == null || a == null) throw new NullPointerException();
  472.         if (_users.containsKey(user) || _users.contains(a)) throw new IllegalArgumentException("Account already existing / username taken");
  473.         for(String key : _users.keySet())
  474.             if (_users.get(key).sameEmail(a)) throw new IllegalArgumentException("Email already in use");
  475.         if (user.length() >= 16) throw new IllegalArgumentException("Username too long");
  476.        
  477.         _users.put(user, a);
  478.         _relations.addNode(user);
  479.     }
  480.    
  481.     /* Returns true if user is a key which already exists in this._users, false otherwise */
  482.     public boolean isTaken(String user) {
  483.         //MODIFIES: none
  484.         //EFFECTS:  Returns true if _users contains the key user, false otherwise
  485.         //          if user equals null, it throws a NullPointerException (default exception in Java, unchecked).
  486.        
  487.         if (user == null) throw new NullPointerException();
  488.        
  489.         return _users.containsKey(user);
  490.     }
  491.    
  492.     /* Returns true if there's an account registered registered to the email "email" in this, false otherwise*/
  493.     public boolean isEmailUsed(String email) {
  494.         //MODIFIES: none
  495.         //EFFECTS:  Returns true if _users contains an account which has email as it's email parameter, false otherwise
  496.         //          if email equals null, it throws a NullPointerException (default exception in Java, unchecked).
  497.        
  498.         if (email == null) throw new NullPointerException();
  499.        
  500.         for(String key : _users.keySet())
  501.             if (_users.get(key).getEmail().equals(email)) return true;
  502.         return false;
  503.     }
  504.    
  505.     /* Returns the username associated with the UserAccount containing email as it's email parameter in this, null if no username has email as it's account's parameter*/
  506.     public String getUsernameByEmail(String email) {
  507.         //MODIFIES: none
  508.         //EFFECTS:  Returns the username associated to the UserAccount which has email as it's email parameter in this,
  509.         //              returns null if no username maps to an account which has email as it's parameter
  510.         //          if email equals null, it throws a NullPointerException (default exception in Java, unchecked).
  511.                
  512.         if (email == null) throw new NullPointerException();
  513.        
  514.         for(String key : _users.keySet())
  515.             if (_users.get(key).getEmail().equals(email)) return key;
  516.         return null;
  517.     }
  518.    
  519.     /* Returns the UserAccount value associated to the username user in this._users*/
  520.     public UserAccount getUserAccount(String user) {
  521.         //MODIFIES: none
  522.         //EFFECTS:  Returns a copy of the value mapped to user in this._users,
  523.         //          if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
  524.         //          if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked).
  525.        
  526.         if (user == null) throw new NullPointerException();
  527.         if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
  528.        
  529.         return new UserAccount(_users.get(user));
  530.     }
  531.  
  532.     /* Sets the UserAccount value associated to user in this to a, if user had a previously value mapped to it, it returns the value which was previously mapped, null otherwise*/
  533.     public UserAccount editAccount(String user, UserAccount a) {
  534.         //MODIFIES: _users
  535.         //EFFECTS:  Maps a to the key user in this._users,
  536.         //              if user had a value previously mapped to it in this, it returns that value, null otherwise
  537.         //          if either user or a equals null, it throws a NullPointerException (default exception in Java, unchecked),
  538.         //          if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked),
  539.         //          if updating a changes the email mapped to user, and such email is already mapped to a different key in this._users,
  540.         //              it throws an IllegalArgumentException (default exception in Java, unchecked).
  541.        
  542.         if (user == null || a == null) throw new NullPointerException();
  543.         if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
  544.        
  545.         if (!_users.get(user).sameEmail(a))
  546.             for(String key : _users.keySet())
  547.                 if (!key.equals(user) && _users.get(key).sameEmail(a)) throw new IllegalArgumentException("Email already in use");
  548.        
  549.         return _users.put(user, a);
  550.     }
  551.  
  552.     /* Removes the account associated to user in this*/
  553.     public void deleteAccount(String user) {
  554.         //MODIFIES: _users, _relations
  555.         //EFFECTS:  Removes the mapping which has user as a key in this._users and the corresponding node in this._relations
  556.         //          if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
  557.         //          if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked).
  558.        
  559.         if (user == null) throw new NullPointerException();
  560.         if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
  561.        
  562.         _users.remove(user);
  563.         _relations.removeNode(user);
  564.     }
  565.    
  566.     /* Adds a friendship relation between the accounts u1 and u2 in this*/
  567.     public void addFriendship(String u1, String u2) {
  568.         //MODIFIES: _relations
  569.         //EFFECTS:  Adds the edge {u1, u2} to this._relations (Note that one user can't link to itself)
  570.         //          if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
  571.         //          if u1 equals u2 it throws an IllegalArgumentException (default exception in Java, unchecked),
  572.         //          if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
  573.                
  574.        
  575.         if (u1 == null || u2 == null) throw new NullPointerException();
  576.         if (u1.equals(u2)) throw new IllegalArgumentException("Invalid request");
  577.         if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
  578.        
  579.         _relations.addEdge(u1, u2);
  580.     }
  581.    
  582.     /* Removes the friendship relation between u1 and u2 in this*/
  583.     public void removeFriendship(String u1, String u2) {
  584.         //MODIFIES: _relations
  585.         //EFFECTS:  Removes the edge {u1; u2} from this._relations if u1 and u2 had an edge between them, it does nothing otherwise
  586.         //          if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
  587.         //          if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
  588.        
  589.         if (isFriend(u1, u2));
  590.             _relations.removeEdge(u1, u2);
  591.     }
  592.    
  593.     /* Returns true if u1 and u2 have a friendship relation in this, false otherwise*/
  594.     public boolean isFriend(String u1, String u2) {
  595.         //MODIFIES: none
  596.         //EFFECTS:  Returns true if {u1; u2} is an existing edge in this._relations, false otherwise
  597.         //          if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
  598.         //          if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
  599.        
  600.         if (u1 == null || u2 == null) throw new NullPointerException();
  601.         if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
  602.         return _relations.containsEdge(u1, u2);
  603.     }
  604.    
  605.     /* Returns a Vector containing the list of usernames corresponding to accounts which have a friendship relation to the account mapped to user in this*/
  606.     public Vector<String> getFriends(String user) {
  607.         //MODIFIES: none
  608.         //EFFECTS:  Returns a Vector<String> containing the usernames u which appear in a {user; u} edge in this._relations
  609.         //          if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
  610.         //          if user isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
  611.        
  612.         if (user == null) throw new NullPointerException();
  613.         if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
  614.        
  615.         Vector<String> _adj = _relations.getAdjacents(user);
  616.        
  617.         return _adj;
  618.     }
  619.    
  620.     /* Returns the friendship distance between u1 and u2 (which is the distance between the nodes representing the two accounts in this, seen as a graph structure)*/
  621.     public Integer getFriendDistance (String u1, String u2) {
  622.         //MODIFIES: none
  623.         //EFFECTS:  Returns the distance between the nodes u1 and u2 in this._relations
  624.         //          if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
  625.         //          if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
  626.        
  627.         if (u1 == null || u2 == null) throw new NullPointerException();
  628.         if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
  629.        
  630.         return _relations.distance(u1, u2);
  631.     }
  632.    
  633.     /* Returns a String representing this */
  634.     public String toString() {
  635.         //MODIFIES: none
  636.         //EFFECTS:  Returns a string containing a representation of this
  637.        
  638.         String _out = "";
  639.         for(String key : _users.keySet())
  640.             _out += "<" + key + "; " + _users.get(key).toString() + "> ";
  641.        
  642.         return _out + "\n\n" + _relations.toString();
  643.     }
  644.    
  645.     /* Returns true if this and o represent the same SocialNetwork, false otherwise */
  646.     public boolean equals(Object o) {
  647.         //MODIFIES: none
  648.         //EFFECTS:  Returns true if this and o represent the same socialnetwork, false otherwise
  649.         //          if o equals null, it throws a NullPointerException (default exception in Java, unchecked).
  650.                
  651.         if (o == null) return false;
  652.         SocialNetwork conv;
  653.        
  654.         try {
  655.             conv = (SocialNetwork)o;
  656.         }
  657.         catch (ClassCastException exc)  {   return false;   }
  658.        
  659.         if (!this._relations.equals(conv._relations)) return false;
  660.         if (this._users.size() != conv._users.size()) return false;
  661.         for(String key : this._users.keySet())
  662.             if (!conv._users.containsKey(key) || !conv._users.get(key).equals(this._users.get(key))) return false;
  663.        
  664.         return true;
  665.     }
  666. }
  667.  
  668. import java.util.Scanner;
  669.  
  670. public class TestMyGraph {
  671.  
  672.     public static void main(String[] args) {
  673.         Scanner terminalInput = new Scanner(System.in);
  674.         MyGraph<String> g = new MyGraph<String>();
  675.        
  676.         String input = new String();
  677.         do {
  678.             System.out.println("Comandi:\naddnode\nremovenode\nremoveedge\ndistance\ndiameter\nexit");
  679.             input = terminalInput.nextLine();
  680.             if (input.equals("addnode"))
  681.             {
  682.                 System.out.println("nodo?");
  683.                 System.out.println(
  684.                         g.addNode(terminalInput.nextLine())
  685.                         );
  686.             } else if (input.equals("addedge"))
  687.             {
  688.                 System.out.println("inserisci due nodi (uno per riga)");
  689.                 System.out.println(
  690.                         g.addEdge(terminalInput.nextLine(), terminalInput.nextLine())
  691.                         ); 
  692.             } else if (input.equals("removenode")) {
  693.                 System.out.println("nodo?");
  694.                 System.out.println(
  695.                         g.removeNode(terminalInput.nextLine())
  696.                         );
  697.             } else if (input.equals("removeedge")) {
  698.                 System.out.println("inserisci due nodi (uno per riga)");
  699.                 System.out.println(
  700.                         g.removeEdge(terminalInput.nextLine(), terminalInput.nextLine())
  701.                         );
  702.             } else if (input.equals("distance")) {
  703.                 System.out.println("nodo sorgente?");
  704.                 System.out.println(
  705.                         g.distance(terminalInput.nextLine(), terminalInput.nextLine())
  706.                         );
  707.             } else if (input.equals("diameter")) {
  708.                 System.out.println("stampo il diametro:?");
  709.                 System.out.println(
  710.                         g.diameter()
  711.                         );
  712.             }
  713.            
  714.         } while (!input.equals("exit"));
  715.         System.out.println("PROGRAM END");
  716.         terminalInput.close();
  717.     }
  718.  
  719. }
  720.  
  721.  
  722. public class TestSocialNetwork {
  723.  
  724.     public static void main(String[] args) {
  725.         SocialNetwork social = new SocialNetwork();
  726.        
  727.         UserAccount user1 = new UserAccount("Mario", "Rossi", "mrossi@email.com");
  728.         UserAccount user2 = new UserAccount("Luigi", "Verdi", "lverdi@email.com");
  729.         UserAccount user3 = new UserAccount("John" , "Smith", "jsmith@email.com");
  730.         UserAccount user4 = new UserAccount("Maria", "Bianc", "mbianc@email.com");
  731.        
  732.         social.addAccount("mrossi", user1);
  733.         social.addAccount("lverdi", user2);
  734.         social.addAccount("mbianc", user4);
  735.        
  736.         //social.addAccount("mrossi", new UserAccount("test", "test", "test@test.te"));     // Nome utente esistente
  737.         //social.addAccount("test", user1);                                                 // Account esistente
  738.         //social.addAccount("test", new UserAccount("test", "test", "mrossi@email.com"));   // Email già in uso
  739.         //social.addAccount("abcdefghijklmnop", new UserAccount("test", "test", "test"));   // Nome utente troppo lungo
  740.        
  741.         System.out.println(social.isTaken("mrossi"));                                       // true
  742.         System.out.println(social.isTaken("test"));                                         // false
  743.        
  744.         System.out.println(social.isEmailUsed("mrossi@email.com"));                         // true
  745.         System.out.println(social.isEmailUsed("test@test.te"));                             // false
  746.        
  747.         System.out.println(social.getUsernameByEmail("mrossi@email.com"));                  // mrossi
  748.         System.out.println(social.getUsernameByEmail("test@test.te"));                      // null
  749.        
  750.         //social.getUserAccount("test");                                                    // Nome utente inesistente
  751.         System.out.println(social.getUserAccount("mrossi"));                                // user1.toString()
  752.        
  753.         //social.editAccount("test", new UserAccount("test", "test", "test@test.te"));      // Nome utente inesistente
  754.         //social.editAccount("mrossi", new UserAccount("test", "test", "lverdi@email.com"));// Email in uso
  755.         social.editAccount("lverdi", user3);                                                // Aggiorno user2 a user3
  756.        
  757.         //social.deleteAccount("test");                                                     // Nome utente inesistente
  758.         social.addAccount("test", new UserAccount("test", "test", "test@test.te"));         // Aggiungo account "test"
  759.         social.deleteAccount("test");                                                       // Rimuovo account "test"
  760.        
  761.         //social.addFriendship("mrossi", "mrossi");                                         // Richiesta non valida
  762.         //social.addFriendship("mrossi", "test");                                           // Nome utente inesistente
  763.         social.addFriendship("mrossi", "lverdi");                                           // Aggiungo l'amicizia "mrossi" - "lverdi"
  764.        
  765.         //social.isFriend("mrossi", "test");                                                // Nome utente inesistente
  766.         System.out.println(social.isFriend("mrossi", "lverdi"));                            // true
  767.        
  768.         //social.getFriends("test");                                                        // Nome utente inesistente
  769.         System.out.println(social.getFriends("mrossi").toString());                         // [lverdi]
  770.        
  771.         //social.removeFriendship("mrossi", "test");                                        // Nome utente inesistente
  772.         social.removeFriendship("mrossi", "lverdi");                                        // Rimuovo l'amicizia "mrossi" - "lverdi"
  773.         System.out.println(social.isFriend("mrossi", "lverdi"));                            // false
  774.        
  775.         //social.getFriendDistance("mrossi", "test");                                       // Nome utente inesistente
  776.         social.addFriendship("mrossi", "lverdi");                                           // Aggiungo l'amicizia "mrossi" - "lverdi"
  777.         social.addFriendship("lverdi", "mbianc");                                           // Aggiungo l'amicizia "lverdi" - "mbianc"
  778.         System.out.println(social.getFriendDistance("mrossi", "mbianc"));                   // 2    (path da "mrossi" -> "lverdi" -> "mbianc")
  779.         System.out.println(social.toString());                                              // Stampa la struttura di social
  780.     }
  781.  
  782. }
Add Comment
Please, Sign In to add comment