Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface Graph<E> {
- //OVERVIEW: The data type Graph<E> represents a set of homogeneous items
- // each element has type E, and they are organized using an undirected graph structure
- //TYPICAL ELEMENT: G = (V, E), where V contains the vertexes and E contains the edges in G
- // and each edge is an unordered pair in VxV
- // V = {vertex_1, ... , vertex_n}
- // E = {{x1; y1}, ... , {x_m; y_m}}
- /* 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 */
- public boolean addNode(E elem) throws NullPointerException;
- //MODIFIES: V
- //EFFECTS: If V doesn't contain elem, it adds elem to V and returns true,
- // it returns false without modifying this otherwise.
- // if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
- /* 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 */
- public boolean addEdge(E x, E y) throws NullPointerException, IllegalArgumentException;
- //MODIFIES: E
- //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,
- // it returns false without modifying this if E already contains {x; y}.
- // if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either x or y aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
- /* 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 */
- public boolean removeNode(E elem) throws NullPointerException;
- //MODIFIES: V, E
- //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,
- // it returns false without modifying this otherwise.
- // if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
- /* If {x; y} is an existing edge in this, it removes {x; y} from the set E and returns true, it returns false otherwise */
- public boolean removeEdge(E x, E y) throws NullPointerException, IllegalArgumentException;
- //MODIFIES: E
- //EFFECTS: If E contains {x; y}, it removes {x; y} from E and returns true,
- // it returns false without modifying this otherwise.
- // if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
- }
- import java.util.*;
- public class MyGraph<E> implements Graph<E> {
- //OVERVIEW: A set of homogeneous items each with type E,
- // organized using an undirected graph structure
- //AF(c):= G = (V, E) where
- // V = {c._values.get(i) | 0 <= i < c._nodeCount }
- // 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())}
- //RI(c):= c._values != null && c._adj != null && (c._adj.get(i) != null) for each 0 <= i < c._nodeCount
- // && c._values.size() == c._adj.size() == c._nodeCount && c._nodeCount >= 0
- // && 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
- // && c._adj.get(i).get(j) != null for each (i, j) such that (0 <= i < c._nodeCount) && (0 <= j < c._adj.get(i).size())
- // && for each (i, j) such that 0 <= i < j < c._nodeCount ==> c._values.get(i) != c._values.get(j)
- // && 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)
- // && 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
- // && for each (i, j) such that (0 <= i < c._nodeCount && 0 <= j < c._adj.get(i).size()) ==> there is one h such that
- // (0 <= h < c._adj.get(c._adj.get(i).get(j)).size()) && h == i
- private Vector<E> _values;
- private Vector<Vector<Integer>> _adj;
- private Integer _nodeCount;
- /* Instantiates this to an empty graph (a graph where both E and V have no elements) */
- public MyGraph() {
- //MODIFIES: _values, _adj, _nodeCount
- //EFFECTS: Sets both _values and _adj to empty lists and _nodeCount to 0 representing an empty graph
- _values = new Vector<E>();
- _adj = new Vector<Vector<Integer>>();
- _nodeCount = 0;
- }
- /* 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 */
- public boolean addNode(E elem) throws NullPointerException {
- //MODIFIES: _values, _adj, _nodeCount
- //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,
- // it increments _nodeCount and returns true. It returns false without modifying this otherwise.
- // if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (elem == null) throw new NullPointerException();
- if (_values.indexOf(elem) < 0) {
- _values.add(elem);
- _nodeCount++;
- _adj.add(new Vector<Integer>());
- return true;
- }
- return false;
- }
- /* 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 */
- public boolean addEdge(E x, E y) throws NullPointerException, IllegalArgumentException {
- //MODIFIES: _adj
- //EFFECTS: if (x, y) already has a corresponding node in this, it returns false without modifying this, if not
- // it adds y to the list of vertexes adjacent to x and vice versa
- // if x equals y, it skips adding a duplicate adjacent vertex
- // if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either x or y aren't already contained in _values, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (x == null || y == null) throw new NullPointerException();
- if (!(_values.contains(x) && _values.contains(y))) throw new IllegalArgumentException();
- int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
- Vector<Integer> adj_x = _adj.get(ind_x);
- if (adj_x.indexOf(ind_y) >= 0) return false;
- adj_x.add(ind_y);
- if (ind_x != ind_y) //this avoids the duplicate edge in case the user is adding a {x, x} edge
- _adj.get(ind_y).add(ind_x);
- return true;
- }
- /* 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 */
- public boolean removeNode(E elem) throws NullPointerException {
- //MODIFIES: _values, _adj, _nodeCount
- //EFFECTS: if _values doesn't contain elem, it returns false without modifying this,
- // 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
- // if elem equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (elem == null) throw new NullPointerException();
- int index = _values.indexOf(elem);
- if (index < 0) return false;
- for(Integer el : _adj.get(index))
- if (el != index) _adj.get(el).removeElement(index);
- _adj.remove(index);
- _values.remove(index);
- _nodeCount--;
- return true;
- }
- /* If {x; y} is an existing edge in this, it removes {x; y} from the set E and returns true, it returns false otherwise */
- public boolean removeEdge(E x, E y) throws NullPointerException, IllegalArgumentException {
- //MODIFIES: _adj
- //EFFECTS: if (x, y) doesn't have a corresponding edge in this, it returns false without modifying this,
- // otherwise, it proceeds by removing x from the list of y's adjacent nodes, and vice versa.
- // if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (x == null || y == null) throw new NullPointerException();
- int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
- if (ind_x < 0 || ind_y < 0) throw new IllegalArgumentException();
- if (!_adj.get(ind_x).contains(ind_y)) return false;
- _adj.get(ind_x).removeElement(ind_y);
- if (ind_x != ind_y) //if x == y, there is only one adjacent representation to be removed
- _adj.get(ind_y).remove(ind_x);
- return true;
- }
- /* If both src and dst are nodes in this, it returns the distance between src and dst, returning -1 if those aren't connected*/
- public int distance(E src, E dst) throws NullPointerException, IllegalArgumentException {
- //MODIFIES: none
- //EFFECTS: it returns the distance between src and dst (the length of the shortest path from src to dst)
- // if src and dst aren't connected it returns -1
- // if either src or dst equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either src or dst aren't already contained in _values, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (src == null || dst == null) throw new NullPointerException();
- if (!(_values.contains(src) && _values.contains(dst))) throw new IllegalArgumentException();
- return bfs_getDistance(_values.indexOf(src))[_values.indexOf(dst)];
- }
- /* 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*/
- public int diameter() {
- //MODIFIES: none
- //EFFECTS: It returns the diameter of this, calculated by comparing the distance between every pair of nodes
- // it returns -1 if _values is empty
- int _max = -1;
- int[] el_dist;
- for (int i = 0; i < _nodeCount; i++) {
- el_dist = bfs_getDistance(i);
- for (int x : el_dist)
- if (x > _max) _max = x;
- }
- return _max;
- }
- /* It returns cardinality of the set V in this*/
- public int nodeCount() {
- //MODIFIES: none
- //EFFECTS: It returns the value of this._nodeCount
- return _nodeCount;
- }
- /* It returns true if x is a node in this, false otherwise*/
- public boolean containsNode(E x) {
- //MODIFIES: none
- //EFFECTS: It returns true if _values contains x, false otherwise
- // if x equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (x == null) throw new NullPointerException();
- return _values.contains(x);
- }
- /* It returns true if {x; y} is an edge in this, false otherwise*/
- public boolean containsEdge(E x, E y) {
- //MODIFIES: none
- //EFFECTS: It returns true if this contains the edge {x; y}, false otherwise
- // if either x or y equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either x or y equals aren't already contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (x == null || y == null) throw new NullPointerException();
- int ind_x = _values.indexOf(x), ind_y = _values.indexOf(y);
- if (ind_x < 0 || ind_y < 0) throw new IllegalArgumentException();
- return _adj.get(ind_x).contains(ind_y);
- }
- /* It returns a list containing the String representation of each node adjacent to x in this*/
- public Vector<String> getAdjacents (E x) {
- //MODIFIES: none
- //EFFECTS: It returns a new Vector<String> containing the String representation of each node in this which is adjacent to x
- // if x equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if x isn't contained in V, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (x == null) throw new NullPointerException();
- int ind_x;
- if ((ind_x = _values.indexOf(x)) < 0) throw new IllegalArgumentException();
- Vector<String> _out = new Vector<String>();
- for (Integer a : _adj.get(ind_x)) _out.add(_values.get(a).toString());
- return _out;
- }
- /* It returns a String representation of the sets V and E in this*/
- public String toString(){
- //MODIFIES: none
- //EFFECTS: It returns a String containing a visualization of the vertexes and edges in this
- String v = "V = {", e = "E = {";
- for (E el : _values) v += el.toString() + "; ";
- for (int i = 0; i < _nodeCount; i++)
- for(Integer el : _adj.get(i))
- if (el >= i) e += "{" + _values.get(i).toString() + "; " + _values.get(el).toString() + "} ";
- return v + "}\n" + e + "}";
- }
- /* It returns true if this and g represent the same graph, false otherwise*/
- @SuppressWarnings("unchecked")
- public boolean equals(Object g) {
- //MODIFIES: none
- //EFFECTS: It returns true if this and g represent the same graph, false otherwise,
- // if e equals null, it throws a NullPointerException (default exception in Java, unchecked.
- if (g == null) return false;
- MyGraph<E> conv;
- int index;
- try {
- conv = (MyGraph<E>)g;
- }
- catch (ClassCastException exc) { return false; }
- if (_nodeCount != conv._nodeCount) return false;
- for (int i = 0; i < _nodeCount; i++) {
- index = conv._values.indexOf(_values.get(i));
- if (index < 0) return false;
- for (Integer ref : _adj.get(i))
- if (!conv._adj.get(index).contains(ref)) return false;
- }
- return true;
- }
- // Private/ Protected methods below:
- /* Esegue una BFS su this partendo dal nodo di indice source e restituisce le distanze da essa in un array*/
- private int[] bfs_getDistance(int source) {
- LinkedList<Integer> queue = new LinkedList<Integer>();
- Integer el = source;
- int[] status = new int[_values.size()], _distance = new int[_values.size()];
- //0 = non_visitato;
- //1 = in_visita
- //2 = visitato
- for (int i = 0; i < _values.size(); i++)
- _distance[i] = -1;
- queue.add(source);
- _distance[source] = 0;
- status[source] = 1;
- do
- {
- for (Integer x : _adj.get(el))
- if (status[x] == 0) {
- status[x] = 1; //marco ogni adiacente come in visita
- _distance[x] = _distance[el] + 1;
- queue.addLast(x);
- }
- status[el] = 2; //marco el come visitato
- try {
- el = queue.removeFirst();
- } catch (NoSuchElementException e) { el = -1; }
- } while (el != -1);
- return _distance;
- }
- }
- public class UserAccount {
- //OVERVIEW: The type UserAccount represents a set of values associated to some parameters which identify a person's account.
- //TYPICAL ELEMENT: P (P being a person's profile) where:
- // P.FirstName := The first name of P's owner
- // P.LastName := The last name of P's owner
- // P.Email := The email which P's owner used in P
- //AF(c):= P where:
- // P.FirstName = c._name
- // P.LastName = c._surname
- // P.Email = c._email
- //RI(c):= c._name != null && c._surname != null && c._email != null
- // && c._name.length() <= 20 && c._surname.length() <= 20
- private String _name, _surname, _email;
- /* Instantiates this to a new UserAccount (setting every value to given parameters) */
- public UserAccount(String name, String surname, String email) {
- //MODIFIES: _name, _surname, _email
- //EFFECTS: Sets _name, _surname and _email to given parameters
- // if either name, surname or email equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either name or surname has a length > 20, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (name == null || surname == null || email == null) throw new NullPointerException();
- if (name.length() > 20 || surname.length() > 20) throw new IllegalArgumentException("Name / Surname too long");
- _name = name;
- _surname = surname;
- _email = email;
- }
- /* Instantiates this to a new UserAccount (copying each value from a given UserAccount) */
- public UserAccount(UserAccount a) {
- //MODIFIES: _name, _surname, _email
- //EFFECTS: Sets _name, _surname and _email to a._name, a._surname and a._email respectively
- // if a equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (a == null) throw new NullPointerException();
- _name = a._name;
- _surname = a._surname;
- _email = a._email;
- }
- /* Returns the first name value in this */
- public String getName() {
- //MODIFIES: none
- //EFFECTS: Returns this._name
- return _name;
- }
- /* Returns the last name value in this */
- public String getSurame() {
- //MODIFIES: none
- //EFFECTS: Returns this._surname
- return _surname;
- }
- /* Returns the email value in this */
- public String getEmail() {
- //MODIFIES: none
- //EFFECTS: Returns this._email
- return _email;
- }
- /* It returns true if this and a have the same email value, false otherwise */
- public boolean sameEmail(UserAccount a){
- //MODIFIES: none
- //EFFECTS: It returns true if this._email equals a._email, false otherwise.
- if (a == null) throw new NullPointerException();
- return _email.equals(a._email);
- }
- /* It returns a String representation of this*/
- public String toString() {
- //MODIFIES: none
- //EFFECTS: It returns a String containing a visualization of _name, _surname and _email from this
- return _surname + ", " + _name + " | " + _email;
- }
- /* It returns true if this and e represent the same UserAccount, false otherwise*/
- public boolean equals(Object e) {
- //MODIFIES: none
- //EFFECTS: It returns true if e can be converted to a UserAccount value and has each value equal to this, false otherwise
- // if e equals null, it throws a NullPointerException (default exception in Java, unchecked.
- if (e == null) return false;
- try {
- UserAccount conv = (UserAccount)e;
- return _email.equals(conv._email)
- && _name.equals(conv._name)
- && _surname.equals(conv._surname);
- }
- catch (ClassCastException exc) { return false; }
- }
- }
- import java.util.Hashtable;
- import java.util.Vector;
- public class SocialNetwork {
- //OVERVIEW: The type SocialNetwork represents a set of UserAccounts organized in an undirected graph structure, where each edge represents a friendship relation.
- // It is based on a Facebook-like structure, where a friendship relation is mutual
- //TYPICAL ELEMENT: S = (A, R), where A contains the user's accounts and R contains the relations represented by the edges of the graph
- // 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
- // E = {{x1; y1}, ... , {x_m; y_m}} where each edge is a set composed of two usernames contained in A
- //AF(c):= S = (A, R) where
- // A = {<k, c._users.get(k)> | for each key k in c._users.keySet() }
- // R = c._relations.E as friendship relations are directly implemented as the set of edges in the MyGraph parameter _relations
- //RI(c):= c._users != null && c._relations != null
- // && c._users.size() == c._relations.nodeCount()
- // && for each key k in c._users.keySet() ==> k != null && c._users.get(k) != null && k.length() < 16
- // && 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
- // && for each key k in c._users.keySet() ==> c._relations.containsNode(k) == true
- // && for each node n in c._relations.V ==> c._users.keySet().contains(n) == true
- private Hashtable<String, UserAccount> _users;
- private MyGraph<String> _relations;
- /* Instantiates this to a new empty SocialNetwork (containing no account and no relations) */
- public SocialNetwork(){
- //MODIFIES: _users, _relations
- //EFFECTS: Sets _users and _relations to an empty Hashtable and an empty MyGraph respectively
- _users = new Hashtable<String, UserAccount>();
- _relations = new MyGraph<String>();
- }
- /* Adds the pair <user, a> to this.A */
- public void addAccount(String user, UserAccount a) {
- //MODIFIES: _users, _relations
- //EFFECTS: Maps the key user to the UserAccount a in this._users and adds user as a new node to _relations
- // if either user or a equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if user is a key already existing in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
- // if a is already mapped in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
- // if a shares it's email with an existing value in this._users, it throws an IllegalArgumentException (default exception in Java, unchecked),
- // if user's length is more or equal to 16, it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (user == null || a == null) throw new NullPointerException();
- if (_users.containsKey(user) || _users.contains(a)) throw new IllegalArgumentException("Account already existing / username taken");
- for(String key : _users.keySet())
- if (_users.get(key).sameEmail(a)) throw new IllegalArgumentException("Email already in use");
- if (user.length() >= 16) throw new IllegalArgumentException("Username too long");
- _users.put(user, a);
- _relations.addNode(user);
- }
- /* Returns true if user is a key which already exists in this._users, false otherwise */
- public boolean isTaken(String user) {
- //MODIFIES: none
- //EFFECTS: Returns true if _users contains the key user, false otherwise
- // if user equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (user == null) throw new NullPointerException();
- return _users.containsKey(user);
- }
- /* Returns true if there's an account registered registered to the email "email" in this, false otherwise*/
- public boolean isEmailUsed(String email) {
- //MODIFIES: none
- //EFFECTS: Returns true if _users contains an account which has email as it's email parameter, false otherwise
- // if email equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (email == null) throw new NullPointerException();
- for(String key : _users.keySet())
- if (_users.get(key).getEmail().equals(email)) return true;
- return false;
- }
- /* 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*/
- public String getUsernameByEmail(String email) {
- //MODIFIES: none
- //EFFECTS: Returns the username associated to the UserAccount which has email as it's email parameter in this,
- // returns null if no username maps to an account which has email as it's parameter
- // if email equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (email == null) throw new NullPointerException();
- for(String key : _users.keySet())
- if (_users.get(key).getEmail().equals(email)) return key;
- return null;
- }
- /* Returns the UserAccount value associated to the username user in this._users*/
- public UserAccount getUserAccount(String user) {
- //MODIFIES: none
- //EFFECTS: Returns a copy of the value mapped to user in this._users,
- // if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (user == null) throw new NullPointerException();
- if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
- return new UserAccount(_users.get(user));
- }
- /* 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*/
- public UserAccount editAccount(String user, UserAccount a) {
- //MODIFIES: _users
- //EFFECTS: Maps a to the key user in this._users,
- // if user had a value previously mapped to it in this, it returns that value, null otherwise
- // if either user or a equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked),
- // if updating a changes the email mapped to user, and such email is already mapped to a different key in this._users,
- // it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (user == null || a == null) throw new NullPointerException();
- if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
- if (!_users.get(user).sameEmail(a))
- for(String key : _users.keySet())
- if (!key.equals(user) && _users.get(key).sameEmail(a)) throw new IllegalArgumentException("Email already in use");
- return _users.put(user, a);
- }
- /* Removes the account associated to user in this*/
- public void deleteAccount(String user) {
- //MODIFIES: _users, _relations
- //EFFECTS: Removes the mapping which has user as a key in this._users and the corresponding node in this._relations
- // if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if user isn't a key in this._users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (user == null) throw new NullPointerException();
- if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
- _users.remove(user);
- _relations.removeNode(user);
- }
- /* Adds a friendship relation between the accounts u1 and u2 in this*/
- public void addFriendship(String u1, String u2) {
- //MODIFIES: _relations
- //EFFECTS: Adds the edge {u1, u2} to this._relations (Note that one user can't link to itself)
- // if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if u1 equals u2 it throws an IllegalArgumentException (default exception in Java, unchecked),
- // if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (u1 == null || u2 == null) throw new NullPointerException();
- if (u1.equals(u2)) throw new IllegalArgumentException("Invalid request");
- if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
- _relations.addEdge(u1, u2);
- }
- /* Removes the friendship relation between u1 and u2 in this*/
- public void removeFriendship(String u1, String u2) {
- //MODIFIES: _relations
- //EFFECTS: Removes the edge {u1; u2} from this._relations if u1 and u2 had an edge between them, it does nothing otherwise
- // if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (isFriend(u1, u2));
- _relations.removeEdge(u1, u2);
- }
- /* Returns true if u1 and u2 have a friendship relation in this, false otherwise*/
- public boolean isFriend(String u1, String u2) {
- //MODIFIES: none
- //EFFECTS: Returns true if {u1; u2} is an existing edge in this._relations, false otherwise
- // if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (u1 == null || u2 == null) throw new NullPointerException();
- if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
- return _relations.containsEdge(u1, u2);
- }
- /* Returns a Vector containing the list of usernames corresponding to accounts which have a friendship relation to the account mapped to user in this*/
- public Vector<String> getFriends(String user) {
- //MODIFIES: none
- //EFFECTS: Returns a Vector<String> containing the usernames u which appear in a {user; u} edge in this._relations
- // if user equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if user isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (user == null) throw new NullPointerException();
- if (!_users.containsKey(user)) throw new IllegalArgumentException("Username not found");
- Vector<String> _adj = _relations.getAdjacents(user);
- return _adj;
- }
- /* 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)*/
- public Integer getFriendDistance (String u1, String u2) {
- //MODIFIES: none
- //EFFECTS: Returns the distance between the nodes u1 and u2 in this._relations
- // if either u1 or u2 equals null, it throws a NullPointerException (default exception in Java, unchecked),
- // if either u1 or u2 isn't a key in _users it throws an IllegalArgumentException (default exception in Java, unchecked).
- if (u1 == null || u2 == null) throw new NullPointerException();
- if (!(_users.containsKey(u1) && _users.containsKey(u2))) throw new IllegalArgumentException("Username not found");
- return _relations.distance(u1, u2);
- }
- /* Returns a String representing this */
- public String toString() {
- //MODIFIES: none
- //EFFECTS: Returns a string containing a representation of this
- String _out = "";
- for(String key : _users.keySet())
- _out += "<" + key + "; " + _users.get(key).toString() + "> ";
- return _out + "\n\n" + _relations.toString();
- }
- /* Returns true if this and o represent the same SocialNetwork, false otherwise */
- public boolean equals(Object o) {
- //MODIFIES: none
- //EFFECTS: Returns true if this and o represent the same socialnetwork, false otherwise
- // if o equals null, it throws a NullPointerException (default exception in Java, unchecked).
- if (o == null) return false;
- SocialNetwork conv;
- try {
- conv = (SocialNetwork)o;
- }
- catch (ClassCastException exc) { return false; }
- if (!this._relations.equals(conv._relations)) return false;
- if (this._users.size() != conv._users.size()) return false;
- for(String key : this._users.keySet())
- if (!conv._users.containsKey(key) || !conv._users.get(key).equals(this._users.get(key))) return false;
- return true;
- }
- }
- import java.util.Scanner;
- public class TestMyGraph {
- public static void main(String[] args) {
- Scanner terminalInput = new Scanner(System.in);
- MyGraph<String> g = new MyGraph<String>();
- String input = new String();
- do {
- System.out.println("Comandi:\naddnode\nremovenode\nremoveedge\ndistance\ndiameter\nexit");
- input = terminalInput.nextLine();
- if (input.equals("addnode"))
- {
- System.out.println("nodo?");
- System.out.println(
- g.addNode(terminalInput.nextLine())
- );
- } else if (input.equals("addedge"))
- {
- System.out.println("inserisci due nodi (uno per riga)");
- System.out.println(
- g.addEdge(terminalInput.nextLine(), terminalInput.nextLine())
- );
- } else if (input.equals("removenode")) {
- System.out.println("nodo?");
- System.out.println(
- g.removeNode(terminalInput.nextLine())
- );
- } else if (input.equals("removeedge")) {
- System.out.println("inserisci due nodi (uno per riga)");
- System.out.println(
- g.removeEdge(terminalInput.nextLine(), terminalInput.nextLine())
- );
- } else if (input.equals("distance")) {
- System.out.println("nodo sorgente?");
- System.out.println(
- g.distance(terminalInput.nextLine(), terminalInput.nextLine())
- );
- } else if (input.equals("diameter")) {
- System.out.println("stampo il diametro:?");
- System.out.println(
- g.diameter()
- );
- }
- } while (!input.equals("exit"));
- System.out.println("PROGRAM END");
- terminalInput.close();
- }
- }
- public class TestSocialNetwork {
- public static void main(String[] args) {
- SocialNetwork social = new SocialNetwork();
- UserAccount user1 = new UserAccount("Mario", "Rossi", "mrossi@email.com");
- UserAccount user2 = new UserAccount("Luigi", "Verdi", "lverdi@email.com");
- UserAccount user3 = new UserAccount("John" , "Smith", "jsmith@email.com");
- UserAccount user4 = new UserAccount("Maria", "Bianc", "mbianc@email.com");
- social.addAccount("mrossi", user1);
- social.addAccount("lverdi", user2);
- social.addAccount("mbianc", user4);
- //social.addAccount("mrossi", new UserAccount("test", "test", "test@test.te")); // Nome utente esistente
- //social.addAccount("test", user1); // Account esistente
- //social.addAccount("test", new UserAccount("test", "test", "mrossi@email.com")); // Email già in uso
- //social.addAccount("abcdefghijklmnop", new UserAccount("test", "test", "test")); // Nome utente troppo lungo
- System.out.println(social.isTaken("mrossi")); // true
- System.out.println(social.isTaken("test")); // false
- System.out.println(social.isEmailUsed("mrossi@email.com")); // true
- System.out.println(social.isEmailUsed("test@test.te")); // false
- System.out.println(social.getUsernameByEmail("mrossi@email.com")); // mrossi
- System.out.println(social.getUsernameByEmail("test@test.te")); // null
- //social.getUserAccount("test"); // Nome utente inesistente
- System.out.println(social.getUserAccount("mrossi")); // user1.toString()
- //social.editAccount("test", new UserAccount("test", "test", "test@test.te")); // Nome utente inesistente
- //social.editAccount("mrossi", new UserAccount("test", "test", "lverdi@email.com"));// Email in uso
- social.editAccount("lverdi", user3); // Aggiorno user2 a user3
- //social.deleteAccount("test"); // Nome utente inesistente
- social.addAccount("test", new UserAccount("test", "test", "test@test.te")); // Aggiungo account "test"
- social.deleteAccount("test"); // Rimuovo account "test"
- //social.addFriendship("mrossi", "mrossi"); // Richiesta non valida
- //social.addFriendship("mrossi", "test"); // Nome utente inesistente
- social.addFriendship("mrossi", "lverdi"); // Aggiungo l'amicizia "mrossi" - "lverdi"
- //social.isFriend("mrossi", "test"); // Nome utente inesistente
- System.out.println(social.isFriend("mrossi", "lverdi")); // true
- //social.getFriends("test"); // Nome utente inesistente
- System.out.println(social.getFriends("mrossi").toString()); // [lverdi]
- //social.removeFriendship("mrossi", "test"); // Nome utente inesistente
- social.removeFriendship("mrossi", "lverdi"); // Rimuovo l'amicizia "mrossi" - "lverdi"
- System.out.println(social.isFriend("mrossi", "lverdi")); // false
- //social.getFriendDistance("mrossi", "test"); // Nome utente inesistente
- social.addFriendship("mrossi", "lverdi"); // Aggiungo l'amicizia "mrossi" - "lverdi"
- social.addFriendship("lverdi", "mbianc"); // Aggiungo l'amicizia "lverdi" - "mbianc"
- System.out.println(social.getFriendDistance("mrossi", "mbianc")); // 2 (path da "mrossi" -> "lverdi" -> "mbianc")
- System.out.println(social.toString()); // Stampa la struttura di social
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement