Commit edfb606e authored by trh010's avatar trh010
Browse files

added functionality to AdjacencyList.java

parent e0afcb6c
......@@ -11,19 +11,67 @@ public class AdjacencyList {
}
public void addNode(String newWord) {
int newHandle = adjList.size() - 1;
ArrayList<Integer> neighbors = findAndSetNeighbors(newWord, newHandle);
Vertex newVertex = new Vertex(newWord, newHandle, neighbors);
adjList.add(newVertex);
}
private ArrayList<Integer> findAndSetNeighbors(String newWord, int newHandle) {
ArrayList<Integer> neighbors = new ArrayList<Integer>();
for (int i = 0; i < adjList.size(); i++) {
Vertex testVertex = adjList.get(i);
if (areRelated(testVertex.getKey(), newWord)) {
testVertex.addNeighbor(newHandle);
neighbors.add(i);
}
}
return neighbors;
}
/**
* Tests if two strings should be neighbors to each other. Two string should
* be neighbors if
*
* @param a
* @param b
* @return
*/
public boolean areRelated(String a, String b) {
if (a.length() != b.length())
System.err.println("When testing if two strings are related, they "
+ "should have the same length.");
int numDifferences = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i))
numDifferences++;
}
if (numDifferences <= 2)
return true;
else
return false;
}
public ArrayList<Integer> getNeighbors(Integer vertexHandle) {
return adjList.get(vertexHandle).getNeighbors();
}
public String neighborsToString(Vertex v) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < v.getNeighbors().size(); i++) {
int neighborHandle = v.getNeighbors().get(i);
String neighborKey = adjList.get(neighborHandle).getKey();
out.append(neighborKey + ", ");
}
return out.toString();
}
public String toString() {
String out = "";
out += "Handle Key | Neighbors \n";
out += "------------------|------------\n";
for (int i = 0; i < adjList.size(); i++) {
out += String.format("%5d %5s", i, adjList.get(i).getKey())
out += String.format("%5d %5s", i, adjList.get(i).getKey())
+ " |\n";
}
return out;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment