Solved

Auto increment an alphanumeric id

Posted on 2009-05-06
11
2,182 Views
Last Modified: 2013-12-17
I need to Increment an ID based on the following "array" of characters...

"0123456789BCDFGHJKLMNPQRSTVWXYZ"

The ID starts with a "P" followed by four characters i.e., P0000

increment would like like P0009, P000B, P000C, P000D, P000F...P0019, P001B, and so on...
0
Comment
Question by:revstudio
  • 6
  • 4
11 Comments
 
LVL 31

Expert Comment

by:Frosty555
ID: 24318499
Try this out
        private void Form1_Load(object sender, EventArgs e)

        {

            string x = "ZZZZ9";

            MessageBox.Show(incrementString(x));

        }
 

        public string incrementString(string input)

        {
 

            char[] c = input.ToCharArray();

            int i = c.Length -1;
 

            bool overflow = false;

            bool nextdigit = false;

            do

            {

                if( i < 0 ) {

                    nextdigit = true;

                    overflow = false;

                }else{

                    c[i]++;
 

                    if (c[i] == ':') {

                        c[i] = 'A';     // jump from ":" to "A" in ascii table

                    }
 

                    if( c[i] > 'Z' ) {

                        // roll over to next digit

                        c[i] = '0';

                        overflow = true;

                        i--;

                    } else {

                        overflow = false;

                    }

                }

            } while (overflow);
 

            string output;

            if (nextdigit)

            {

                output = String.Concat("1", new string(c));

            }

            else

            {

                output = new string(c);

            }
 

            return output;

        }

Open in new window

0
 
LVL 31

Expert Comment

by:Frosty555
ID: 24318538
I don't know if you intended to intentionally skip those letters in your array above.  (e.g. skipping over A, and going straight to B)

If you did, you can put those jumps in the code. See attached.
        public string incrementString(string input)

        {
 

            char[] c = input.ToCharArray();

            int i = c.Length -1;
 

            bool overflow = false;

            bool nextdigit = false;

            do

            {

                if( i < 0 ) {

                    nextdigit = true;

                    overflow = false;

                }else{

                    c[i]++;
 
 

                    // Skipping characters and jumps

                    if (c[i] == ':')

                    {

                        c[i] = 'B';  

                    }

                    if (c[i] == 'E')

                    {

                        c[i] = 'F';

                    }

                    if (c[i] == 'I')

                    {

                        c[i] = 'J';

                    }

                    if (c[i] == 'O')

                    {

                        c[i] = 'P'; 

                    }

                    if (c[i] == 'U')

                    {

                        c[i] = 'V'; 

                    }
 
 

                    if( c[i] > 'Z' ) {

                        // roll over to next digit

                        c[i] = '0';

                        overflow = true;

                        i--;

                    } else {

                        overflow = false;

                    }

                }

            } while (overflow);
 

            string output;

            if (nextdigit)

            {

                output = String.Concat("1", new string(c));

            }

            else

            {

                output = new string(c);

            }
 

            return output;

        }

Open in new window

0
 

Author Comment

by:revstudio
ID: 24318876
Had to convert to VB but it doesn't seem to work

If I leave i as integer = c.length -1 (which makes sense to me) then I get and out of bounds error

If i change it to c.length -2 (which doesnt make sense to me) then:

If I pass in a string "P0051" it should increment to "P0052" (this is any easy one) it returns the same value


    Public Function incrementString(ByVal input As String) As String
 

        Dim c As Char() = input.ToCharArray()

        Dim i As Integer = c.Length - 2
 

        Dim overflow As Boolean = False

        Dim nextdigit As Boolean = False

        Do

            If i < 0 Then

                nextdigit = True

                overflow = False

            Else

                System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
 

                ' Skipping characters and jumps

                If c(i) = "A"c Then

                    c(i) = "B"c

                End If

                If c(i) = "E"c Then

                    c(i) = "F"c

                End If

                If c(i) = "I"c Then

                    c(i) = "J"c

                End If

                If c(i) = "O"c Then

                    c(i) = "P"c

                End If

                If c(i) = "U"c Then

                    c(i) = "V"c

                End If
 

                If c(i) > "Z"c Then

                    ' roll over to next digit

                    c(i) = "0"c

                    overflow = True

                    System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)

                Else

                    overflow = False

                End If

            End If

        Loop While overflow
 

        Dim output As String

        If nextdigit Then

            output = [String].Concat("1", New String(c))

        Else

            output = New String(c)

        End If
 

        Return output

    End Function

Open in new window

0
 

Author Comment

by:revstudio
ID: 24319044
I created a C# test applicaiton and it works fine. Can anyone help me figure out what is wrong in my conversion?
0
 

Author Comment

by:revstudio
ID: 24319114
I think it can be resolved with an equivalent to c(i)++

That was the reason for the System.Math.Max(System.Threading.Interlocked.Increment(i), i + 1) and System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)
 
 
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:revstudio
ID: 24319872
Modified code from http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_23100704.html

Create a Base31 Converter :)

   Function NextID(ByVal InputNumber As String) As String

        Dim J, K, DecimalValue, X, MaxBase, InputNumberLength As Integer

        Dim NumericBaseData, OutputValue As String

        NumericBaseData = "0123456789BCDFGHJKLMNPQRSTVWXYZ"

        MaxBase = (NumericBaseData.Length)
 

        InputNumberLength = InputNumber.Length

        DecimalValue = 0

        For J = 1 To InputNumberLength

            For K = 1 To MaxBase

                If Mid(InputNumber, J, 1) = Mid(NumericBaseData, K, 1) Then

                    DecimalValue = DecimalValue + Int((K - 1) * (MaxBase ^ (InputNumberLength - J)) + 0.5)

                End If

            Next K

        Next J
 

        '*/ Add 1 to Decimal Equivalent of the Current Base31 number /*

        DecimalValue = DecimalValue + 1
 

        ' Convert the Decimal Value + 1 back to Base31 Value /*

        OutputValue = ""

        While DecimalValue > 0

            X = Int(((DecimalValue / 31) - Int(DecimalValue / 31)) * 31 + 1.5)

            OutputValue = Mid(NumericBaseData, X, 1) + OutputValue

            DecimalValue = Int(DecimalValue / 31)

        End While

        Return OutputValue
 

    End Function

Open in new window

0
 
LVL 31

Accepted Solution

by:
Frosty555 earned 250 total points
ID: 24327045
revstudio,

See the attached code, worked fine for me. No out of bounds error.

Also note that the NextID() code you just posted fails on any number greater than 7 digits. E.g. incrementing "ZZZZZZZ" fails with an arithmetic overflow.

My function works on strings of unbounded length.
    Public Function incrementString(ByVal input As String) As String
 

        Dim c As Char() = input.ToCharArray()

        Dim i As Integer = c.Length - 1
 

        Dim overflow As Boolean = False

        Dim nextdigit As Boolean = False

        Do

            If i < 0 Then

                nextdigit = True

                overflow = False

            Else

                c(i) = Chr(Asc(c(i)) + 1)
 

                ' Skipping characters and jumps

                If c(i) = "A"c Then

                    c(i) = "B"c

                End If

                If c(i) = "E"c Then

                    c(i) = "F"c

                End If

                If c(i) = "I"c Then

                    c(i) = "J"c

                End If

                If c(i) = "O"c Then

                    c(i) = "P"c

                End If

                If c(i) = "U"c Then

                    c(i) = "V"c

                End If
 

                If c(i) > "Z"c Then

                    ' roll over to next digit

                    c(i) = "0"c

                    overflow = True

                    System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)

                Else

                    overflow = False

                End If

            End If

        Loop While overflow
 

        Dim output As String

        If nextdigit Then

            output = [String].Concat("1", New String(c))

        Else

            output = New String(c)

        End If
 

        Return output

    End Function

Open in new window

0
 

Author Closing Comment

by:revstudio
ID: 31578654
Thanks for the help.
0
 

Author Comment

by:revstudio
ID: 24327277
Solution was missing ...

                ' Skipping characters and jumps
                If c(i) = ":"c Then
                    c(i) = "B"c
                End If
 
0
 
LVL 2

Expert Comment

by:indmillert
ID: 32340324
I've been playing with this for a little while now and I guess I don't really understand how it's working because I would like it to run like:

A,B,C,D.....Z,0,1,2,3,4,5,6,7,8,9

I can't seem to tweak the code to work correctly. Can anyone clarify?
0
 
LVL 31

Expert Comment

by:Frosty555
ID: 32349227
The code takes advantage of the fact that alphanumeric digits can be represented in ascii using integer values.

http://www.asciitable.com/

So to increment a particular digit, you convert it to its ascii code (e.g. "A"->65), then increment the number (e.g. 65->66), then convert from the ascii code back to an actual letter/number (e.g. 66->"B"). This is done with the ASC() and CHR() functions.

In ASCII, numbers 0-9 come before the uppercase letters A-Z, so that's the pattern it is going to follow.

There is no easy way to modify the above code that I can see to have the numbers come after the letters, since now you can't take advantage of the ASCII table.  So you will need to "reinvent" the wheel and create your own table of digits instead of using ASCII.

You will need to rewrite this line:

c(i) = Chr(Asc(c(i)) + 1)

And have it instead look up the index of the characters from an array that you have defined, increment the index, then re-evaluate the new character using your array. Effectively this is like making your own "table" of letters instead of using the built in ASCII table and rewriting the CHR() and ASC() functions.

c(i) = GetIndexFromLetter(GetLetterFromIndex(c(i)) + 1)

You'll also need to rewrite the "rollover" and "concatenate" parts of the code since those don't line up anymore with what you're trying to do:



Below, you need to instead roll over to the next digit when you hit the number "9", since "9" is the last digit in your sequence. Better yet, you should use the last item in your array of characters.

-------------

                If c(i) > "Z"c Then
                    ' roll over to next digit
                    c(i) = "0"c
                    overflow = True
                    System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)
                Else
                    overflow = False
                End If

-------------

And below, you would want to concatenate "A" to the end, since "A" is the first digit in the sequence now instead of "1". Or better yet you should use the 0th index in your array of characters.

-------------

        Dim output As String
        If nextdigit Then
            output = [String].Concat("1", New String(c))
        Else
            output = New String(c)
        End If

-------------
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now