Go and exercise your brain ... can you find the coding bug for jumping?

Go and exercise your brain ... can you find the coding bug for jumping?

Here's a small problem for you. You are tasked to implemented in the Jump cipher, which jumps a given number of characters, so if we have a skip of 3, then:

The social network said its members had expressed concerns that they 
were missing 'important updates' from the people they cared about.

becomes:

T cleo ii mrh psdoesh eweii mrnuasfmhpp eceauT cleo ii mrh psdoesh 
eweii mrnuasfmhpp eceauT cleo ii mrh psdoesh eweii mrnuasfmhpp eceau

So you implement a small function (with a break glass value, just in case we go into an infinite loop):

        public static string jump(int n, string s)
        {
            int counter = 0;
            int len = s.Length;
            int ptr = 0;
            string str = "";
            int max = 100;
            while (counter < len)
            {
                ptr = ptr % len;
                str = str + s[ptr];
                counter = counter + 1;
                ptr = ptr + n;
                if (counter > max) break;
            }
            return str;
        }

where n is the jump number and s is the string to perform the jump. So if we try "hello" with a jump of 3, we get:

hleol

but then I try "handle" and you get:

hdhdhd

where there are two letters repeating. So I check to see if there's an even number of characters and reject others, and that seems to solve the problem. But I try "abcdefgh" and get:

abcdefgh

which works, but " "abcdefhi", and I get:

adgadgadg

I scratch my head ... what should I have done?

With a skip of 3, where is this? ... "fldnnia"

With a skip of 2, which is this word? "fradowr"

Once you've solved it, here's a challenge for you ... here. Hopefully it won't have bugs!

要查看或添加评论,请登录

Prof Bill Buchanan OBE FRSE的更多文章

社区洞察