Codewars字符画Kata随机测试失败问题求助
我在完成Codewars上的字符画Kata时,实现的blockPrint函数能通过所有给定测试,但随机测试(输入最多30个随机字符)时会出现空格丢失、大量随机字符异常,多次尝试后错误还会累积。之前提问被标记为“含剧透”,猜测可能是JavaScript数据处理或测试机制存在认知盲区,附上实现代码:
function blockPrint(input){ if (input.trim()=="") return""; const string=input.trim().toUpperCase(); //trims off spaces and converts to uppercase const map=[]; let output=""; // Uses the exact requirements given in expected output as shown below let pos=0; map[0]=" AAA BBBB CCC DDDD EEEEE FFFFF GGG H H IIIII JJJJJ K K L M M N N OOO PPPP QQQ RRRR SSS TTTTT U U V V W W X X Y Y ZZZZZ"; map[1]="A A B B C C D D E F G G H H I J K K L MM MM NN N O O P P Q Q R R S S T U U V V W W X X Y Y Z"; map[2]="A A B B C D D E F G H H I J K K L M M M N N O O P P Q Q R R S T U U V V W W X X Y Y Z "; map[3]="AAAAA BBBB C D D EEEEE FFFFF G GGG HHHHH I J KK L M M N N N O O PPPP Q Q RRRR SSS T U U V V W W W X Y Z "; map[4]="A A B B C D D E F G G H H I J K K L M M N N O O P Q Q Q R R S T U U V V W W W X X Y Z "; map[5]="A A B B C C D D E F G G H H I J K K L M M N NN O O P Q QQ R R S S T U U V V W W W X X Y Z "; map[6]="A A BBBB CCC DDDD EEEEE F GGG H H IIIII JJJJ K K LLLLL M M N N OOO P QQQQ R R SSS T UUU V W W X X Y ZZZZZ"; for (let i=0;i<7;i++){ for(let j=0;j<string.length-1;j++){ pos=(string.charCodeAt(j)-65)*6; // works out which bit to add if (pos>=0 && pos<=91){ // and if its not a space output+=(map[i].slice(pos,pos+6)); // adds it } //just do up till the last char because of test requirement for no trailing spaces if((pos/6)+65<65) { // or if it is a space output+=" "; // adds a space of 6 "spaces" } } pos=(string.charCodeAt((string.length)-1)-65)*6; // finds the last char output+=(map[i].slice(pos,pos+6)).trimEnd(); // adds the bit with its "end" trimmed off as per the test requirements if(i<6) {output+="\n";} //this to ensure no added carriage returns are added at the end as per test requirements } console.log(output); return output; }
问题原因分析
字符映射表位宽不匹配
手动定义的map中每个字符串,每个字母对应的位宽并非严格6个字符。比如map[0]里"A"的部分是" AAA "(6个字符),但后续"B"的部分实际只有5个字符,导致按pos=(charCode-65)*6计算的切片位置完全错位。处理多个字符时,错位会不断累积,最终出现大量随机字符或空格丢失。非A-Z字符处理逻辑漏洞
用(pos/6)+65<65判断空格,等价于pos<0,会把所有charCode<65的字符(数字、符号等)都当作空格处理;但如果遇到charCode>90的字符(比如[),此时pos=(91-65)*6=156,既不满足切片条件,也不满足空格判断条件,会直接跳过该字符的输出,导致该行长度缺失,后续行全部错位。trimEnd()破坏行对齐
对最后一个字符的切片结果执行trimEnd(),会去掉末尾空格,导致该行长度比其他行短。比如最后一个字符是"A",切片结果" AAA "会被修剪为" AAA",少了2个空格,后续行的字符位置全部偏移,累积出更多错误。有效字符范围判断错误
用pos<=91判断有效字母,但Z的charCode是90,对应的pos=(90-65)*6=150,远大于91,导致Z的切片条件不成立,且不会被当作空格处理,直接跳过输出,造成Z字符无法正确显示。
内容的提问来源于stack exchange,提问作者bigsegs

