1. 程式人生 > 其它 >【Codewars】Rail Fence Cipher: Encoding and Decoding

【Codewars】Rail Fence Cipher: Encoding and Decoding

題目地址:https://www.codewars.com/kata/58c5577d61aefcf3ff000081/train/javascript

*需要注意的一點:當rail=3的時候每次都是跨固定的距離,但如果用4就會發現不一樣。

const encodeRailFenceCipher=(str,num)=>{
    const arr=str.split('');
    const len=arr.length;
    const resultArr=[];
    const maxGap=(num-2)*2+2;
    for(var i=0;i<num;i++){
        var initialInterval;
        if(i===0||i===num-1){
            initialInterval=maxGap;
        }else{
            initialInterval=maxGap-i*2;
        }
        var tempInterval=initialInterval;
        var k=i;
        do{
            resultArr.push(arr[k]);
            k=k+tempInterval;
            if(i!==0&&i!==num-1){
                tempInterval=maxGap-tempInterval;
            }
        }while(k<len);
    }
    return resultArr.join('');
}

const decodeRailFenceCipher=(str,num)=>{
    let index=0;
    const maxGap=(num-2)*2+2;
    const arr=str.split('');
    const len=arr.length;
    const res=[];
    for(var i=0;i<num;i++){
       let initialInterval=maxGap-2*i;
        if(i===num-1){
            initialInterval=maxGap;
        } 
        var tempInterval=initialInterval;
        var k=i;
        do{
            if(index<len){
                res[k]=arr[index];
                index++;
                k=k+tempInterval;
                if(i!==0&&i!==num-1){
                    tempInterval=maxGap-tempInterval;
                }
            }
        }while(k<len);
    }
    return res.join('');
}

const givenStr="SFHBJSAKHDEWQIUEHIWQEH";
const res=encodeRailFenceCipher(givenStr,8);
const res2=decodeRailFenceCipher(res,8);
console.log(res);