Increment a value from AAA to ZZZ with cyclic rotation

Posted by www.openidfrance.frfxkim on Stack Overflow See other posts from Stack Overflow or by www.openidfrance.frfxkim
Published on 2010-06-15T16:31:20Z Indexed on 2010/06/15 17:02 UTC
Read the original article Hit count: 299

Filed under:
|

Hi all,

I need to code a method that increment a string value from AAA to ZZZ with cyclic rotation (next value after ZZZ is AAA)

Here is my code:

    public static string IncrementValue(string value) {
        if (string.IsNullOrEmpty(value) || value.Length != 3) {
            string msg = string.Format("Incorrect value ('{0}' is not between AAA and ZZZ)", value);
            throw new ApplicationException(msg);
        }
        if (value == "ZZZ") {
            return "AAA";
        }
        char pos1 = value[0];
        char pos2 = value[1];
        char pos3 = value[2];

        bool incrementPos2 = false;
        bool incrementPos1 = false;

        if (pos3 == 'Z') {
            pos3 = 'A';
            incrementPos2 = true;
        } else {
            pos3++;
        }

        if (incrementPos2 && pos2 == 'Z') {
            pos2 = 'A';
            incrementPos1 = true;
        } else {
            if (incrementPos2) {
                if (pos2 == 'Z') {
                    pos2 = 'A';
                    incrementPos1 = true;
                }
                pos2++;
            }
        }

        if (incrementPos1) {
            pos1++;
        }

        return pos1.ToString() + pos2.ToString() + pos3.ToString();
    }

I know this piece of code is quite dirty and not very efficient but I dont know how to do it properly.

How is secured this snippet? (this will only run on windows plaform)

How can I optimize-it and make it more readable ?

Thanks for your comments

© Stack Overflow or respective owner

Related posts about c#

Related posts about increment