我正在进行编码挑战,以加密字符串并在指定的字符长度后返回带空格的加密字符串。另外,剩下的剩余字符应使用额外的空格填充,以使其达到指定字符长度。 这是我尝试做的:
const str =
"If man was meant to stay on the ground, god would have given us roots.";
class SquareCode {
constructor(text) {
this.text = text;
}
// Remove spaces and punctuation
normalizeString() {
return this.text.replace(/[^\w]|_/g, "").toLowerCase();
}
// Get number of columns
size() {
return Math.ceil(Math.sqrt(this.normalizeString().length));
}
// Split string into chunks
chunks() {
const pattern = new RegExp(`.{1,${this.size()}}`, "g");
return this.normalizeString().match(pattern);
}
// Encrypt String
encryptString() {
let code = "";
const chunks = this.chunks();
for (let i = 0; i < this.size(); ++i) {
for (let j = 0; j < chunks.length; ++j) {
code += chunks[j].slice(i, i + 1);
const rowLength = this.size()-1;
if (code.replace(/\s/g, '').length % rowLength === 0) code += ' ';
}
}
return code;
}
}
const work = new SquareCode(str);
console.log(work.encryptString());
这是我得到的输出:“ imtgdvs恐惧者mayoogo anouuio ntnnlvt wttddes aohghns seoau”
这是预期的输出:“ imtgdvs恐惧者mayoogo anouuio ntnnlvt wttddes aohghn ssauau”
这是提供更好环境的挑战的链接 Challenge
答案 0 :(得分:0)
尝试:
const str =
"If man was meant to stay on the ground, god would have given us roots.";
class SquareCode {
constructor(text) {
this.text = text;
}
// Remove spaces and punctuation
normalizeString() {
return this.text.replace(/[^\w]|_/g, "").toLowerCase();
}
// Get number of columns
size() {
return Math.ceil(Math.sqrt(this.normalizeString().length));
}
// Split string into chunks
chunks() {
const pattern = new RegExp(`.{1,${this.size()}}`, "g");
return this.normalizeString().match(pattern);
}
// Encrypt String
encryptString() {
let code = "";
const chunks = this.chunks();
const size = this.size();
console.log(chunks);
for (let i = 0; i < size; ++i) {
for (let j = 0; j < chunks.length; ++j) {
code += chunks[j].slice(i, i + 1);
}
code += ' '
}
return code;
}
}
const work = new SquareCode(str);
console.log(work.encryptString());
当块长度小于大小时,Slice返回一个空字符串,并在代码中的每个“单词”之后添加一个空格。尽管在说明中的示例中,“ aohghn”后似乎有2个空格,而不仅仅是一个空格,但是在您的问题中,对于所需的输出,只有一个空格:
“ imtgdvs恐惧者mayoogo anouuio ntnnlvt wttddes aohghn ssauau”
vs。
“ imtgdvs恐惧者mayoogo anouuio ntnnlvt wttddes aohghn(2个空格)ssauau”