天天看點

js資料結構hashMap -----hashMap

// 散清單  hashMap
        // 散列函數
        /**
        給定一個key參數,我們就能根據組成key的每個字元的ASCII碼值
        的和得到一個數字。是以, 首先需要一個變量來存儲這個總和(行{1})。
        然後,周遊key(行{2})并将從ASCII表中查到 的每個字元對應的ASCII值加到
        hash變量中(可以使用JavaScript的String類中的charCodeAt 方法——行{3})。
        最後,傳回hash值。為了得到比較小的數值,我們會使用hash值和一個任意 數
        做除法的餘數(mod)
        **/
        var loseloseHashCode = function (key) {
            var hash = 0;                          //{1}
            for (var i = 0; i < key.length; i++) { //{2}
                hash += key.charCodeAt(i);         //{3}
            }
            return hash % 37; //{4}
        };

        var djb2HashCode = function (key) {
            var hash = 5381; //{1}
            for (var i = 0; i < key.length; i++) { //{2}
                hash = hash * 33 + key.charCodeAt(i); //{3}
            }
            return hash % 1013
        }
        function HashTable() {
            var table = [];
            this.put = function (key, value) {
                var position = djb2HashCode(key); //{5}
                console.log(position + ' - ' + key); //{6}
                table[position] = value; //{7}
            };
            this.get = function (key) {
                return table[djb2HashCode(key)];
            };
            this.remove = function (key) {
                table[djb2HashCode(key)] = undefined;
            }
            this.print = function () {
                for (var i = 0; i < table.length; ++i) { //{1}
                    if (table[i] !== undefined) {        //{2}
                        console.log(i + ": " + table[i]);//{3}
                    }
                }
            };
        }
        var hash = new HashTable();
        hash.put('Gandalf', '[email protected]');
        hash.put('John', '[email protected]');
        hash.put('Tyrion', '[email protected]');

        console.log(hash.get('Gandalf'));
        console.log(hash.get('Loiane'));
        /**
        有時候,一些鍵會有相同的散列值。不同的值在散清單中對應相同位置的時候,
        我們稱其為沖突。例如,我們看看下面的代碼會得到怎樣的輸出結果
        **/
        var hash = new HashTable();
        hash.put('Gandalf', '[email protected]');
        hash.put('John', '[email protected]');
        hash.put('Tyrion', '[email protected]');
        hash.put('Aaron', '[email protected]');
        hash.put('Donnie', '[email protected]');
        hash.put('Ana', '[email protected]');
        hash.put('Jonathan', '[email protected]');
        hash.put('Jamie', '[email protected]');
        hash.put('Sue', '[email protected]');
        hash.put('Mindy', '[email protected]');
        hash.put('Paul', '[email protected]');
        hash.put('Nathan', '[email protected]');
        hash.print()      

轉載于:https://www.cnblogs.com/vali/p/9603132.html

繼續閱讀