我喜欢这种加密风格。我在Code.org 应用程序中模拟了解决方案以进行测试等。
加密
首先我清理了一点加密代码。我发现几个变量名稍微有点不对劲。
onEvent("button_encrypt", "click", function(encrypt) {
var text = getText("text_input1");
var encrypted = "";
var i = 0;
while (i < text.length) {
encrypted = encrypted + text.charAt(i);
i = i + 2;
}
i = 1;
while (i < text.length) {
encrypted = encrypted + text.charAt(i);
i = i + 2;
}
//changed ID, do to design
setText("resultLbl", encrypted);
});
解密
我通过获取加密数据,将其分成两半,然后将前面的字母从每一半剥离,来回交替来解决解密问题。
onEvent("decryptBtn", "click", function(){
var text = getText("text_input1");
var decrypt = "";
//break message in half
var half1 = text.substring(0,text.length/2);
var half2 = text.substring(text.length/2);
//Loop through two variables. If one is longer will always be half1.
//Could do this with two index variables, but I did it by shrinking words
while(half1.length > 0){
//add to solution
decrypt = decrypt + half1.substring(0,1);
//cut the letter off the encrypted string once used
half1 = half1.substring(1);
//Repeat for half2
//If protects from edge case of one more letter in half1
if(half2.length > 0){
decrypt = decrypt + half2.substring(0,1);
half2 = half2.substring(1);
}
}
setText("resultLbl", decrypt);
});