数据结构与算法JavaScript描述练习------第8章散列

1. 使用线性探测法创建一个字典,用来保存单词的定义。该程序需要包含两个部分:第一 部分从文本文件中读取一组单词和它们的定义,并将其存入散列表;第二部分让用户输 入单词,程序给出该单词的定义。


function HashTable() { 
	this.table = new Array(137); 
	this.values = [];
	this.simpleHash = simpleHash; 
	this.showDistro = showDistro; 
	this.put = put; 
	this.get = get; 
	this.buildChains = buildChains;
}

function showDistro() {
	console.log("hashtable: ")
	for (var i = 0; i < this.table.length; i++) {
		if (this.table[i] && this.table[i].length > 0) {
			console.log(i + ": " + this.table[i]);
		}
	}
}

function simpleHash(data) {
	var H = 31;
	var total = 0;
	for (var i = 0; i < data.length; i++) {
		total += H * total + data.charCodeAt(i);
	}
	total = total % this.table.length;
	if (total < 0) {
		total += this.table.length - 1;
	}
	console.log("Hash value: " + data + " -> " + total); 
	return parseInt(total);
}

function put(key, data) {
	var pos = this.simpleHash(key);
	while (this.table[pos] != undefined) {
		pos = (pos + 1) % this.table.length;
	} 
	this.table[pos] = key;
	this.values[pos] = data;
}

function get(key) {
	var pos = this.simpleHash(key);
	if (pos > -1) {
		while (this.table[pos] != undefined) {
			if (this.table[pos] == key) {
				return this.values[pos];
			}
			pos = (pos + 1) % this.table.length;
		} 
	}
	return undefined;
}

function loadDefinitions(hashTable, definitions) {
    for (var i = 0; i < definitions.length; i++) {
        var definition = definitions[i];
        var parts = definition.split(': ');
        if (parts.length === 2) {
            var word = parts[0].trim();
            var meaning = parts[1].trim();
            hashTable.put(word, meaning);
        }
    }
}

function queryDefinition(hashTable) {
    var input = prompt("请输入要查询的单词:");
    if (input) {
        var definition = hashTable.get(input);
        if (definition) {
            alert("单词 \"" + input + "\" 的定义是:" + definition);
        } else {
            alert("未找到单词 \"" + input + "\" 的定义。");
        }
    }
}

var definitions = [
    "apple: a fruit that is round and usually red or green",
    "banana: a long curved fruit that grows in clusters and has soft pulpy flesh and yellow skin when ripe",
    "cherry: the small, round fruit of a cherry tree, which is sweet or sour and can be eaten raw or used in cooking"
];

var hTable = new HashTable();
loadDefinitions(hTable, definitions);
queryDefinition(hTable);

2. 使用开链法重新实现练习 1。


function HashTable() { 
	this.table = new Array(137); 
	this.values = [];
	this.simpleHash = simpleHash; 
	this.showDistro = showDistro; 
	this.put = put; 
	this.get = get; 
	this.buildChains = buildChains;
}

function showDistro() {
	console.log("hashtable: ")
	for (var i = 0; i < this.table.length; i++) {
		if (this.table[i] && this.table[i].length > 0) {
			console.log(i + ": " + this.table[i]);
		}
	}
}

function simpleHash(data) {
	var H = 31;
	var total = 0;
	for (var i = 0; i < data.length; i++) {
		total += H * total + data.charCodeAt(i);
	}
	total = total % this.table.length;
	if (total < 0) {
		total += this.table.length - 1;
	}
	console.log("Hash value: " + data + " -> " + total); 
	return parseInt(total);
}

function put(key, data) {
	var pos = this.simpleHash(key);
	var index = 0;
	while (this.table[pos][index] !== undefined || this.table[pos][index + 1] !== undefined) {
		index += 2;
	} 
	this.table[pos][index] = key;
	this.table[pos][index + 1] = data;
}

function get(key) {
	var pos = this.simpleHash(key);
	var index = 0;
	while (this.table[pos][index] !== undefined) {
		if (this.table[pos][index] === key) {
			return this.table[pos][index + 1];
		}
		index += 2;
	} 
	return undefined;
}

function buildChains() {
	for (var i = 0; i < this.table.length; i++) {
		this.table[i] = new Array();
	}
}

function loadDefinitions(hashTable, definitions) {
    for (var i = 0; i < definitions.length; i++) {
        var definition = definitions[i];
        var parts = definition.split(': ');
        if (parts.length === 2) {
            var word = parts[0].trim();
            var meaning = parts[1].trim();
            hashTable.put(word, meaning);
        }
    }
}

function queryDefinition(hashTable) {
    var input = prompt("请输入要查询的单词:");
    if (input) {
        var definition = hashTable.get(input);
        if (definition) {
            alert("单词 \"" + input + "\" 的定义是:" + definition);
        } else {
            alert("未找到单词 \"" + input + "\" 的定义。");
        }
    }
}

var definitions = [
    "apple: a fruit that is round and usually red or green",
    "banana: a long curved fruit that grows in clusters and has soft pulpy flesh and yellow skin when ripe",
    "cherry: the small, round fruit of a cherry tree, which is sweet or sour and can be eaten raw or used in cooking"
];

var hTable = new HashTable();
loadDefinitions(hTable, definitions);
queryDefinition(hTable);

3. 读取一个文本文件,使用散列显示该文件中出现的单词和它们在文件中出现的次数

function preprocessText(text) {
    text = text.toLowerCase();
    text = text.replace(/[^a-z\s]/g, '');
    return text.split(/\s+/);
}


function countWords(hashTable, words) {
    words.forEach(function(word) {
        if (word.trim() !== '') {
            if (hashTable.get(word)) {
                hashTable.values[hashTable.table.indexOf(word)]++;
            } else {
                hashTable.put(word, 1);
            }
        }
    });
}

function displayResults(hashTable) {
    console.log("单词及其出现次数:");
    for (var i = 0; i < hashTable.table.length; i++) {
        if (hashTable.table[i]) {
            console.log(hashTable.table[i] + ": " + hashTable.values[i]);
        }
    }
}

var text = "This is an example text with several words. This text contains repeated words like this and this.";

var hTable = new HashTable();

var words = preprocessText(text);
countWords(hTable, words);
displayResults(hTable);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值