Implementation of hashing
Hash class-Linear detection method function HashTable () {this.table = new Array (137); This.values = []; This.simplehash = Simplehash; This.betterhash = Betterhash; This.showdistro = Showdistro; This.put = put; This.get = Get;} function put (key, data) {Let pos = This.betterhash (key); This.table[pos] = data; if (this.table[pos] = = = undefined) {This.table[pos] = key; This.values[pos] = data; } else {while (This.table[pos]!== undefined) {++pos; } This.table[pos] = key; This.values[pos] = data; }}function get (Key) {//return This.table[this.betterhash (key)]; Let hash =-1; hash = This.betterhash (key); if (hash >-1) {for (Let i = hash; This.table[hash]!== undefined; ++i) {if (this.table[hash] = = = K EY) {return this.values[hash]; }}} return undefined;} function Simplehash (data) {Let total = 0; for (Let i = 0; i < data.length; ++i) {Total + = data.charcodeat (i); } return total% This.table.length;} function Showdistro () {Let n = 0; for (Let i = 0; i < this.table.length; ++i) {if (This.table[i]!== undefined) {console.log (' ${i}: $ {This.table[i]} '); }}}function Betterhash (string) {const H = 7; Let total = 0; for (Let i = 0; i < string.length; ++i) {Total + = H * Total + string.charcodeat (i); } total = total% This.table.length; if (Total < 0) {total + = this.table.length-1; } return parseint (total, 10);}
Practice using linear probing to create a dictionary that holds the definition of a word. The program needs to contain two parts: the first part stores a set of words and their definitions into a hash list; The second part lets the user enter a word, and the program gives the definition of the word.
// 字典类function Dict () { this.hashTable = new HashTable(); this.save = save; this.find = find;}function save (word, description) { this.hashTable.put(word, description);}function find (word) { return this.hashTable.get(word);}// 示例let d = new Dict();d.save('Mazey', 'a strong man.');d.save('Cherrie', 'a beautiful girl.');d.save('John', 'unknown.');console.log(d.find('John')); // unknown.console.log(d.find('Mazey')); // a strong man.console.log(d.find('Ada')); // undefined
JavaScript data structures and algorithms-hashing exercises