Encoding Input Data: ABC - Output: ZBYX
The encoding happens such that the odd numbered letters of the English alphabet are replaced by their alphabetic opposite, even numbered letters are replaced by a combination of that same letter and it's alphabetic opposite (ie. as shown above 'B' is even numbered alphabet so it got replaced as 'BY', A is replaced by Z, C is replaced by X)
I need to decode the encoded output data to get the input (the reverse logic). I wrote the below function but it doesn't quite give me the expected output for all test cases. (eg: When the input is ZBYX, output comes up correctly as ABC, but in other cases such as:
- JQPLO (input) - output comes as QJKL (supposed to come as JKL)
- NMLPK (input) - output comes as MNOP (supposed to come as NOP)
)
How should I refactor the below code so that I get the expected output for all test cases?
let alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function decode(str){
let answer=""
for(let i=0;i<str.length;i++){
if(alpha.indexOf(answer[answer.length-1])%2==0){
if((alpha.indexOf(str[i])+1)%2==0){
continue
}
answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]
}else{
answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]
}
}
return answer
}
JKLyou getQKPO?Jis 10th in the alphabet.answer[answer.length-1]instead ofanswer[i]?