JavaScript資料結構與演算法-散列練習

來源:互聯網
上載者:User

標籤:hashtable   des   console   ==   java   log   post   實現   ons   

散列的實現
// 散列類 - 線性探測法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] === key) {                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);}
練習使用線性探測法建立一個字典,用來儲存單詞的定義。該程式需要包含兩個部分:第一部分將一組單詞和它們的定義儲存進散列表;第二部分讓使用者輸入單詞,程式給出該單詞的定義。
// 字典類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資料結構與演算法-散列練習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.