0

My initial code is 'A0AA' and I need a code/function in C# that will increment it until it goes to 'Z9ZZ'.

for example. first code is 'D9ZZ' the next code should be 'E0AA'

sorry maybe my example is quite confusing.. here's another example.. thanks. first code is 'D9AZ' the next code should be 'D9BA'

Kara
  • 6,115
  • 16
  • 50
  • 57
marvzcosep
  • 23
  • 5
  • be bit more specific. Are there any specifications about the size of your code, number of compulsory numbers etc. – QuestionEverything Mar 17 '14 at 11:28
  • Note that this is basically a 4-digit base-36 counter... assuming that the second digit is alphanumeric rather than only being numeric as in the given examples. – keshlam Mar 18 '14 at 02:26

3 Answers3

1
 string start = "A9ZZ";

 int add = 1;
 string next = String.Concat(start.Reverse().Select((x,i) =>
 {
      char first = i == 2 ? '0' : 'A';
      char last  = i == 2 ? '9' : 'Z';

      if ((x += (char)add) > last)
      {
          return first;
      }
      else
      {
          add = 0;
          return x;
      }
 })
 .Reverse());
GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
1

This should fix it.

private static IEnumerable<string> Increment(string value)
{
    if (value.Length != 4)
        throw new ArgumentException();

    char[] next = value.ToCharArray();
    while (new string(next) != "Z9ZZ")
    {
        next[3]++;
        if (next[3] > 'Z')
        {
            next[3] = 'A';
            next[2]++;
        }
        if (next[2] > 'Z')
        {
            next[2] = 'A';
            next[1]++;
        }
        if (next[1] > '9')
        {
            next[1] = '0';
            next[0]++;
        }
        yield return new string(next);
    }
}

Example of calling this code:

IList<string> values = Increment("A0AA").Take(100).ToList();
foreach (var value in values)
{
    Console.Write(value + " ");
}
default
  • 11,485
  • 9
  • 66
  • 102
0

Here's a pretty clean solution that checks every character starting at the end:

public SomeMethod()
{
    var next = Increment("A2CZ"); // A2DZ
}

public string Increment(string code)
{
    var arr = code.ToCharArray();

    for (var i = arr.Length - 1; i >= 0; i--)
    {
        var c = arr[i];
        if (c == 90 || c == 57)
            continue;

        arr[i]++;
        return new string(arr);
    }

    return code;
}