我正在尝试创建一个函数,它可以从 .txt 文件读取编码消息并将其返回到字符串中。基本上,txt 的格式遵循数字和单词,例如:
3 love
6 computers
2 dogs
4 cats
1 I
5 you
我想要它做的第一件事就是按照金字塔顺序排列数字,如下所示:
1
2 3
4 5 6
数字应该与 .txt 文件中的单词匹配,一旦组织好,金字塔的末端应该写出一个句子,例如使用上面的列表 1: I 3: love 6:computers 写出“我爱计算机” .
到目前为止,这就是我得到的,但它只返回一个值,我不知道为什么
function decode(message_file) {
const fs = require("fs");
const data = fs.readFileSync(message_file, "utf8");
const lines = data.split("\n").filter(Boolean);
const message_words = [];
let current_line = 1;
let current_num = 1;
for (const line of lines) {
const [num, word] = line.split(" ");
if (parseInt(num) == current_num) {
message_words.push(word);
current_line++;
current_num = (current_line + 1) / 2;
}
}
return message_words.join(" ");
}
const decoded_message = decode("message.txt");
console.log(decoded_message);
首先创建一个数组,其中单词位于与文件中的数字相对应的索引处。
然后编写一个循环来实现数字金字塔并输出数组中相应索引处的单词。
function decode(data) {
const lines = data.split("\n").filter(Boolean);
const message_words = [];
lines.forEach(line => {
[index, word] = line.split(' ');
message_words[parseInt(index)] = word;
});
let line_length = 1;
let line_pos = 0;
let output_string = '';
for (let i = 1; i < message_words.length; i++) {
output_string += message_words[i];
line_pos++;
if (line_pos >= line_length) {
output_string += '\n';
line_pos = 0;
line_length++;
} else {
output_string += ' ';
}
}
return output_string;
}
console.log(decode(content));
<script>
let content = `3 love
6 computers
2 dogs
4 cats
1 I
5 you`;
</script>