From 580461a3f5f6b076562da6e8dca1228daf1b0ccb Mon Sep 17 00:00:00 2001
From: Brady James Garvin <bgarvin@cse.unl.edu>
Date: Thu, 29 Nov 2018 09:15:48 -0600
Subject: [PATCH] Updated starter code for 2018 lab.

---
 index.html       |  3 ++-
 js/hash_table.js | 21 +++++++++++++++++----
 js/index.js      | 12 ++++++++++--
 3 files changed, 29 insertions(+), 7 deletions(-)

diff --git a/index.html b/index.html
index f7218eb..0e334b3 100644
--- a/index.html
+++ b/index.html
@@ -9,7 +9,8 @@
 </head>
 
 <body>
-  <div id="result"></div>
+  <div id="time"></div>
+  <div id="freeness"></div>
   <script src="libraries/jquery/jquery.min.js"></script>
   <script src="js/hash_table.js"></script>
   <script src="js/words.js"></script>
diff --git a/js/hash_table.js b/js/hash_table.js
index fb3a37c..37c78d2 100644
--- a/js/hash_table.js
+++ b/js/hash_table.js
@@ -60,6 +60,19 @@ class HashTable {
     return this._size;
   }
 
+  get collisionFreeness() {
+    if (this._size === 0) {
+      return 1.0;
+    }
+    let occupiedBucketCount = 0;
+    for (const bucket of this._buckets) {
+      if (bucket.length > 0) {
+        ++occupiedBucketCount;
+      }
+    }
+    return occupiedBucketCount / this._size;
+  }
+
   has(element) {
     return this._buckets[this._hashFunction(element)].includes(element);
   }
@@ -68,10 +81,10 @@ class HashTable {
     const bucket = this._buckets[this._hashFunction(element)];
     if (!bucket.includes(element)) {
       bucket.push(element);
-    }
-    ++this._size;
-    if (this._size / this._buckets.length > MAXIMUM_LOAD_FACTOR) {
-      this._resize();
+      ++this._size;
+      if (this._size / this._buckets.length > MAXIMUM_LOAD_FACTOR) {
+        this._resize();
+      }
     }
   }
 
diff --git a/js/index.js b/js/index.js
index d85099f..cc6a5c3 100644
--- a/js/index.js
+++ b/js/index.js
@@ -4,11 +4,19 @@
 
 const startTime = Date.now();
 
-const table = new HashTable((word) => 0);
+const table = new HashTable((word) => 0); // TODO: Design a better hash function
+
 for (const word of DICTIONARY) {
   table.add(word);
 }
 
+for (const word of DICTIONARY) {
+  if (!table.has(word)) {
+    throw new Error(`Found an inconsistency in the hash function when applying it to "${word}"`);
+  }
+}
+
 const endTime = Date.now();
 
-$('#result').text(`Constructed hash table of American English words in ${endTime - startTime} ms.`);
+$('#time').text(`Constructed and verified a hash table of American English words in ${endTime - startTime} ms.`);
+$('#freeness').text(`Collision freeness using this hash function: ${(100 * table.collisionFreeness).toFixed(3)}%.`);
-- 
GitLab