zoukankan      html  css  js  c++  java
  • 对学生成绩进行散列

        function HashTable() {
            this.table = new Array(137);
            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 />");
                }
            }
        }
        function getRandomInt(min, max) {//此方法随机获得50-100之间的学生成绩值
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        function genStuData(arr) {
            for ( var i = 0; i < arr.length; ++i) {
                var num = "";
                for ( var j = 1; j <= 9; ++j) {//此循环随机获得学生成绩的ID值
                    num += Math.floor(Math.random() * 10);//注意num是个字符串
                }
                num += getRandomInt(50, 100);//将随机获得的ID值与学生成绩相连接
                arr[i] = num;
            }
        }
        var numStudents = 10;//数组中的数据长度
        var students = new Array(numStudents);
        genStuData(students);
        document.write("Student data: <br />");
        for ( var i = 0; i < students.length; ++i) {
            document.write(students[i].substring(0, 8) + " "
                    + students[i].substring(9) + "<br />");
        }
        document.write("Data distribution: <br />");
        var hTable = new HashTable();
        for ( var i = 0; i < students.length; ++i) {
            hTable.put(students[i]);
        }
        hTable.showDistro();
  • 相关阅读:
    BZOJ 3160 万径人踪灭
    BZOJ 2160 拉拉队排练
    模板 manacher算法
    [Tjoi2016&Heoi2016]求和
    [HZOI 2015]疯狂的机器人
    [BZOJ3456]城市规划
    BZOJ 4372 烁烁的游戏
    洛谷3794 签到题IV
    BZOJ 3730 震波
    BZOJ 4916 神犇和蒟蒻
  • 原文地址:https://www.cnblogs.com/feile/p/5396584.html
Copyright © 2011-2022 走看看