题解 | #记票统计#
记票统计
https://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894
// num 是候选人 人数
while ((num = readline())) {
// 是候选人名字以及得票
let countVotes = readline()
.split(" ")
.map((item) => ({ name: item, vote: 0 }));
readline();
let votes = readline().split(" "); //投票 可以理解为问题 输入描述的第四行
let res = [];
// 把候选人的名字 放到一个数组中
for (let i = 0; i < countVotes.length; i++) {
res.push(new RegExp(`^${countVotes[i].name}$`));
}
let Invalid = 0; //不合法票数
for (let j = 0; j < votes.length; j++) {
let iflegal = 0;
for (let p = 0; p < res.length; p++) {
// 如果候选人的名字在投票中
if (res[p].test(votes[j])) {
iflegal = 1; //这票合法
countVotes[p].vote++; //候选人的票数加1
}
}
// 不是合法的票数
if (!iflegal) {
Invalid++; //不合法票数加1
}
}
// 打印候选人以及得票数
for (let k = 0; k < countVotes.length; k++) {
console.log(`${countVotes[k].name} : ${countVotes[k].vote}`);
}
console.log(`Invalid : ${Invalid}`); //打印不合法票数
}