在看《数据结构与算法JavaScript描述》中的队列这一章节时,涉及到
舞伴分配问题,其中的舞伴数据是存储在.txt文件中,在js文件中,用read
函数读取dancers.txt获取舞伴数据再进行操作,然而我在js中让read去获
取数据时却不成功,我猜可能是我用的是Node.js 提供的 JavaScriptshell
的原因。
于是我想到了json来传递数据。以下是我的代码分析。
首先把跳方块舞的男男女女的姓名存储在json对象中:
var dancers = [
{ sex: "F", names: [ "Allison", "McMillan", "Cheryl", "Ferenback", "Jennifer", "Ingram", "Aurora", "Adney" ]
},
{ sex: "M", names: [ "Frank", "Opitz", "Mason", "McMillan", "Clayton", "Ruff", "Raymond", "Williams", "Bryan", "Frazer", "David", "Durr", "Danny", "Martin" ] }
];
每个舞者信息都被存储在一个Dancer对象中:
function Dancer(name, sex) {
this.name = name;
this.sex = sex;
}
我们需要一个函数,将舞者信息从json对象中读到程序中:
function getDancers(males, females)
{
for (var i = 0; i < dancers.length; ++i)
{
for (var j = 0; j < dancers[i].names.length; ++j) {
if (dancers[i].sex == "F") {
femaleDancers.enqueue(new Dancer(dancers[i].names[j], dancers[i].sex)); }
else {
maleDancers.enqueue(new Dancer(dancers[i].names[j], dancers[i].sex)); }
}
}
}
下一个函数将男性和女性组成舞伴,并且宣布配对结果:
function dance(males, females) {
console.log("The dance partners are:\n");
while (!females.empty() && !males.empty()) {
person = females.dequeue();
console.log("Female dancer is:" + person.name);
person = males.dequeue();
console.log("and the male dancer is:" + person.name);
}
console.log();
}
重要的函数我们已经完成了,接下来我们测试一下:
var maleDancers = new Queue();
var femaleDancers = new Queue();
getDancers(maleDancers, femaleDancers);
dance(maleDancers, femaleDancers);
if (femaleDancers.count() > 0)
{
console.log( "There are" + femaleDancers.count() + "females dancers waiting to dance." );
}
if (maleDancers.count() > 0) {
console.log( "There are " + maleDancers.count() + " males dancers waiting to dance." );
}
这是测试结果,显示最终等待跳舞的数量:
测试结果
网友评论