开发者

shift array by k

i am working on a small java program, its very basic and one of my functions shifts the alphabet by a given key. i have got it working, but its shifting the wrong way, how can i make it shift the other direction?

public static char[] ourAlphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',开发者_JAVA百科'q','r','s','t','u','v','w','x','y','z'};


    public  char[] shiftAlphabet(int key) {

            int length = ourAlphabet.length;

            char[] result = new char[length];

            for (int i=0; i < length; i++)
            {
                result[(i+key+26)%length] = ourAlphabet[i];
            }

            return result;
    }

Im guessing its very simple, but its confused me!

For example; with a key 19 produces; hijklmnopqrstuvwxyzabcdefg

when is should produce; TUVWXYZABCDEFGHIJKLMNOPQRS


Change to:

result[i] = ourAlphabet[(i+key)%length];


It should work if you use result[(i-key+26)%length] = ourAlphabet[i];

However, if length != 26 this would still give a wrong result.

I would therefore replace the 26 by length;

result[(i-key+length)%length] = ourAlphabet[i];


public static char[] ourAlphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};


public  char[] shiftAlphabet(int key) {

        int length = ourAlphabet.length;

        char[] result = new char[length];

        for (int i=0; i < length; i++)
        {
            ourAlphabet[(i+key+26)%length] = result[i];
        }

        return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜