diff --git a/index.html b/index.html index f7218eb611d5353d46c6a22381d35c5682c5bbee..0e334b31d564a91255396fb7f88b4d69a59222fb 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 fb3a37c30961eac5eb3804fbb24a66c1c6bf5de1..37c78d2c7091e17404f35b20fde47009186c4b00 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 d85099f7d84ff8599e34a5fdea779e2f4e0cc1d9..cc6a5c383acb3822e93c612998acf11958391231 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)}%.`);