• 对字符串类型的值进行散列


        function HashTable() {
            this.table = new Array(137);//137——官方比较好的设置数组大小的值
            //this.simpleHash = simpleHash;
            this.betterHash = betterHash;
            this.showDistro = showDistro;
            this.put = put;
            //this.get = get;
        }
        /* function simpleHash(data) {//此种散列方式容易产生碰撞
            var total = 0;
            for ( var i = 0; i < data.length; ++i) {
                total += data.charCodeAt(i);
            }
            return total % this.table.length;
        } */
        function put(data) {
            var pos = this.betterHash(data);//获得数据散列的位置
            this.table[pos] = data;
        }
        function betterHash(data) {//比较好的散列数据的方式,返回散列数据在数组中的位置
            var cons = 31;//此参数的设置是为了避免碰撞,众多算法书中推荐的数值
            var total = 0;
            for ( var i = 0; i < data.length; ++i) {
                total += cons * total + data.charCodeAt(i);
            }
            total = total % this.table.length;
            document.write("Hash value: " + data + " -> " + total + "<br />");//测试是否有相同的散列值
            if (total < 0) {
                total += this.table.length - 1;
            }
            return parseInt(total);
        }
        function showDistro() {        
          for ( var i = 0; i < this.table.length; ++i) { if (this.table[i] != undefined) { document.write(i + ": " + this.table[i]); document.write("<br />"); } } } var someNames = [ "David", "Jennifer", "Donnie", "Raymond", "Cynthia", "Mike", "Clayton", "Danny", "Jonathan" ]; var hTable = new HashTable(); for ( var i = 0; i < someNames.length; ++i) { hTable.put(someNames[i]);//将数组中的数据放入到散列表中 } hTable.showDistro();
  • 相关阅读:
    dal configure 源码分析
    dubbo源码
    mysql replace info 和 auto_increment可能产生的问题
    消息队列总结
    关于系统并发数和QPS的思考
    字符打印流及字节打印流使用
    oracle分组查询二,row_number() over()函数的使用
    oracle表函数使用table function
    Script:10g中显示Active Session Count by Wait Class
    剑指 Offer 61. 扑克牌中的顺子
  • 原文地址:https://www.cnblogs.com/feile/p/5396580.html
Copyright © 2020-2023  润新知