I'm looking for a way of generating an alphabetic sequence:
A, B, C, ..., Z, AA, AB, AC, ..., ZZ.
Can anyone suggest a convenient way of doing this. What data structures can I make use of?
I'd like methods which get the next code in the sequence and then reset the sequence.
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
Since in your current for-loop (after changing seq= to seq+= ) you'll have a sequence like this: 01234567891011... , where numbers > 10 are actually two or three digits, not one. So the total length of your String for 1000 sequential numbers would be 2890.
Java Character isAlphabetic() Method. The isAlphabetic(intcodePoint)method of Character class determines whether the specified character is an alphabet or not. A character is considered to be an alphabet if it has the following characteristics: UPPERCASE_ LETTER.
In Java, the char variable stores the ASCII value of a character (number between 0 and 127) rather than the character itself. The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from 65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122.
A one-line recursive function to generate the string from an integer:
static String str(int i) { return i < 0 ? "" : str((i / 26) - 1) + (char)(65 + i % 26); }
Example usage:
public static void main(String[] args) { for (int i = 0; i < 27*27; ++i) { System.out.println(i + " -> " + str(i)); } }
Output:
0 -> A 1 -> B 2 -> C [...] 24 -> Y 25 -> Z 26 -> AA 27 -> AB [...] 700 -> ZY 701 -> ZZ 702 -> AAA 703 -> AAB [...] 727 -> AAZ 728 -> ABA
I combined Wikipedia's Hexavigesimal#Bijective base-26 and Bijective numeration#Properties of bijective base-k numerals to make this:
import static java.lang.Math.*; private static String getString(int n) { char[] buf = new char[(int) floor(log(25 * (n + 1)) / log(26))]; for (int i = buf.length - 1; i >= 0; i--) { n--; buf[i] = (char) ('A' + n % 26); n /= 26; } return new String(buf); }
With the help of Wolfram Alpha. Maybe it would have been simpler to just use the implementation in the first link though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With