I need to generate character sequences that increment, where each character can be of a different letter or number range. Does anyone know of a library that does such a task? For example:
AAA000_A0
Where A's are any letter A-Z, and 0's are any number 0-9. I need to increment them as well, so for example:
AAA000_A0++ = AAA000_A1
And if you keep going it would carry over like this:
AAA000_A9++ = AAA000_B0
Until it reached:
ZZZ999_Z9
I would decompose the problem to each spot, sort of like a car's odometer:
public class CounterDigit {
private final CounterDigit _higher;
private final String _chars;
private int _index = 0;
public CounterDigit(CounterDigit higher, String chars) {
_higher = higher;
_chars = chars;
}
public CounterDigit(CounterDigit higher, char first, char last) {
this(higher, charRange(first, last));
}
private static String charRange(char first, char last) {
StringBuilder b = new StringBuilder();
for (char c = first; c <= last; ++c) {
b.append(c);
}
return b.toString();
}
public char current() {
return _chars.charAt(_index);
}
public void increment() {
if (++_index >= _chars.length()) {
_index = 0;
if (_higher != null) {
_higher.increment();
}
}
}
}
You can then aggregate an ordered sequence of these:
public class Counter {
private CounterDigit[] _digits;
public Counter(String template) {
CounterDigit recent = null;
_digits = new CounterDigit[template.length()];
for (int i = 0; i < template.length(); ++i) {
char c = template.charAt(i);
if (c == 'A') { recent = new CounterDigit(recent, 'A', 'Z'); }
else if (c == '0') { recent = new CounterDigit(recent, '0', '9'); }
else { recent = new CounterDigit(recent, c, c); }
_digits[i] = recent;
}
}
public void increment() {
_digits[_digits.length-1].increment();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder(_digits.length);
for (CounterDigit digit : _digits) {
b.append(digit.current());
}
return b.toString();
}
}