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();