Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating an alphabetic sequence in Java

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.

like image 739
mip Avatar asked Jan 03 '12 10:01

mip


People also ask

How do you arrange letters alphabetically in Java?

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.

How do you create a sequence in Java?

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.

Is there an alphabet method in Java?

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.

How do you represent a to z in Java?

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.


2 Answers

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 
like image 106
jon-hanson Avatar answered Sep 23 '22 07:09

jon-hanson


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.

like image 39
user988346 Avatar answered Sep 22 '22 07:09

user988346