Search code examples
c#sequence-generators

Generate Sequence A to Z and then 0 to 9, from A to 999


Thanks in advance, I want to generate sequence from A to Z and after that 0 to 9 and after that it will move to AA, AB, AC ..... AZ, A0, A1 .... A9, BA and so on

i had tried to implement it as following

public static string GenerateSequence(List<string> inputList)
    {
        string identifierCode = "A";
        //check if list does not contains any element
        if (!inputList.Any()) return identifierCode;
        //sort codes
        inputList.Sort();
        //get last code
        var lastItem = inputList[inputList.Count - 1];
        //split code
        var splittedChars = lastItem.ToCharArray();
        bool incrementNext = true;
        for (int i = 0; i < splittedChars.Length; i++)
        {
            if (incrementNext)
            {
                var effectedNumber = splittedChars.Length - (i + 1);
                if (effectedNumber >= 0)
                {
                    var charToIncrement = splittedChars[effectedNumber];
                    switch (charToIncrement)
                    {
                        case 'Z':
                            charToIncrement = '0';
                            incrementNext = false;
                            break;
                        case '9':
                            charToIncrement = 'A';
                            incrementNext = true;
                            splittedChars[effectedNumber] = charToIncrement;
                            break;
                        default:
                            charToIncrement++;
                            incrementNext = false;
                            break;
                    }
                    splittedChars[effectedNumber] = charToIncrement;
                }
                else
                {
                    return "A" + splittedChars;
                }
            }
        }

        return new string(splittedChars);
    }

but inputList.Sort() sorts numbers before Alphabets so my code fails after Z


Solution

  • A recursive approach to generate sequence required is as follows

            public static string GenerateSequence(int col)
        {
            if (col>=1 && col <= 36)
            {  
                string schars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                return schars[col-1].ToString();
            }
            int div = col / 36;
            int mod = col % 36;
            if (mod == 0) { mod = 36; div--; }
            return GenerateSequence(div) + GenerateSequence(mod);
        }
    
    
        static void Main(string[] args)
        {
    
            for (int i = 1; i < 250; i++)
            {
                Console.WriteLine(i + "---" + GenerateSequence(i));
            }
    
        }