AlphaNumeric Increment
AlphaNumeric series Increment
Introduction
Background
Many alpha numeric samples increment only numeric part and append alpha as prefix, but the requirement was to increment all characters in a series.
This is usually required if you want to generate some unique varchar
value for a database, or to achieve more combination in short length.
- Numeric 0-9 (Length 2) = 100 combinations
- Numeric A-Z (Length 2) = 676 combinations
- Numeric 0-9|A-Z (Length 2) = 1296 combinations
Also it should have modes to control series generation direction.
Using the Code
Series sequence types are as follows. You may control the direction i.e. numeric first, alpha first or mix modes...
The following sample is for 2 character length.NumericToAlpha
, AlphaToNumeric
and AlphaNumeric
will generate the same result but the generation sequence will be different.
public enum SequenceType
{
/// <summary>
/// 00,01,...,09,0A,...0Z,10,11...,A0,A1,...,ZZ
/// </summary>
NumericToAlpha = 1,
/// <summary>
/// AA,AB,...,AZ,A0,...A9,BA,BB...ZZ,00,01,...99
/// </summary>
AlphaToNumeric = 2,
/// <summary>
/// A0,A1,...,A9,AA,...AZ,B0,B1...ZZ,00,01,...99
/// </summary>
AlphaNumeric = 3,
/// <summary>
/// 00,01,...99
/// </summary>
NumericOnly = 4,
/// <summary>
/// AA,AB,...,ZZ
/// </summary>
AlphaOnly = 5
}
while (keepChecking)
{...
This will convert all to ASCII and iterate on all ASCII values and increments each, while it keeps track to toggle the next ASCII if it first reaches its maximum defined value.
aSCIIValues = ASCIIEncoding.ASCII.GetBytes(KeyCode.ToUpper());
indexToCheck = aSCIIValues.Length - 1;
bool keepChecking = true;
while (keepChecking)
{
aSCIIValues[indexToCheck] = next(aSCIIValues[indexToCheck], Sequence);
if (aSCIIValues[indexToCheck] ==
SingleCharacterMaxValue(Sequence) && indexToCheck != 0)
indexToCheck--;
else
keepChecking = false;
}
KeyCode = ASCIIEncoding.ASCII.GetString(aSCIIValues);
This will return the next ASCII value as per sequence type.
private static byte next(int current, SequenceType sequence)
{
switch (sequence)
{
case SequenceType.NumericToAlpha:
if (current == 57)
current = 65;
else if (current == 90)
current = 48;
else
current++;
break;
case SequenceType.AlphaToNumeric:
if (current == 90)
current = 48;
else if (current == 57)
current = 65;
else
current++;
break;
case SequenceType.AlphaNumeric:
if (current == 57)
current = 65;
else if (current == 90)
current = 48;
else
current++;
break;
case SequenceType.NumericOnly:
if (current == 57)
current = 48;
else
current++;
break;
case SequenceType.AlphaOnly:
if (current == 90)
current = 65;
else
current++;
break;
default:
break;
}
return Convert.ToByte(current);
}