Skip to content

Commit

Permalink
Merge branch 'master' of github.com:rasmus4200/algorithms101
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Rasmusson committed Jan 31, 2020
2 parents aaf57e1 + d0584dc commit 13ac212
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
22 changes: 7 additions & 15 deletions src/main/java/datastructures/HashTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,36 +53,28 @@ public String get(String key) {
// Get the current list of entries
HashEntry entries = data[index];

// if we have existing entries against this key...
if (entries != null) {
// else walk chain until find a match
while (!entries.key.equals(key) && entries.next !=null) {
entries = entries.next;
}
// then return it
return entries.value;
// While there are elements in the linked list...
while (entries != null) {
if (entries.key.equals(key)) // Check for match
return entries.value; // if match found return
entries = entries.next; // else go to next node in chain
}

// it we have no entries against this key...
return null;
return null; // return null if no match found
}

private int getIndex(String key) {
// Get the hash code
int hashCode = key.hashCode();
System.out.println("hashCode = " + hashCode);

// Convert to index
int index = (hashCode & 0x7fffffff) % INITIAL_SIZE;
// int index = hashCode % INITIAL_SIZE;

// Hack to force collision for testing
if (key.equals("John Smith") || key.equals("Sandra Dee")) {
if (key.equals("John Smith") || key.equals("Sandra Dee") || key.equals("Tim Lee")) {
index = 4;
}

System.out.println("index = " + index);

return index;
}

Expand Down
9 changes: 9 additions & 0 deletions src/test/java/datastructures/HashTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,18 @@ public void PutAndGet() {
Assert.assertEquals("521-5030", hashTable.get("Sam Doe"));
Assert.assertEquals("521-9655", hashTable.get("Sandra Dee"));
Assert.assertEquals("418-4165", hashTable.get("Ted Baker"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));

hashTable.toString();
}

@Test
public void Empty() {
Assert.assertEquals(null, hashTable.get("Ted Baker"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));
hashTable.toString();
}

@Test
public void Collision() {
// these keys will collide
Expand All @@ -38,5 +46,6 @@ public void Collision() {

Assert.assertEquals("521-1234", hashTable.get("John Smith"));
Assert.assertEquals("521-9655", hashTable.get("Sandra Dee"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));
}
}

0 comments on commit 13ac212

Please sign in to comment.