Program to generate Excel Sheet Column Sequence

Excel Sheet Column sequence means a sequence like A,B,C..Z,AA,AB..ZZ,AAA...ZZZ..... . The program is very simple to code once we understood the logic. For converting a number to the corresponding string in this sequence, we need to know two things : -

  • How many characters are there in the string.
  • What is the corresponding value of each character.
To find how many characters are there in the string, we should keep on diving the number/26 until it is greater than 0. To get the corresponding value of each character from last, we need to get number mod 26. One tricky thing about this algorithm is that, when we do the modulus of number corresponding to 'Z', we will get 26 mod 26 =0. We can add 26 to the modulus value if we get 0. Also in case of 'Z' , we need to subtract 1 from the result of number/26 so that our loop won't go for an extra iteration.

For generating the Excel Sheet Column sequence to a given number, convert all the numbers from 1 to given number to the corresponding sequence and put in a set and return it.

The program is as follows: -

import java.util.LinkedHashSet;
import java.util.Set;


public class ExcelSheetRowSequence {

public static void main(String args[])
{
System.out.println(" Excel Sheet Row Sequence");
int num=99;
Set<String> sequence = new LinkedHashSet<String>();
sequence = generateValue(num);
System.out.println();
for(String item: sequence)
{
System.out.print(item + "  ");
}
}
public static Set<String> generateValue(int num)
{
Set<String> sequence = new LinkedHashSet<String>();
char temp='A';
char temp1 = 'Z';
int tempnum;
for(int i=1;i<=num;i++)
{  
tempnum=i;
String returnval="";
while(tempnum>0)
{
int val=tempnum%26;
if(val==0)
{
char append=(char) (val+ temp1);
returnval=append + returnval;
tempnum=(tempnum/26) -1;
}
else
{
char append=(char) (val-1 +temp);
returnval= append + returnval;
tempnum=tempnum/26;
}
}
sequence.add(returnval);
}
System.out.println();
return sequence;
}
}


If you have any doubts, please comment below. All queries will be responded within a days time. Thank you for reading.

Similar Programs

1) Program to find the longest sequence in an array - sujithforu.blogspot.com/2012/11/program-to-find-longest-sequence-in.html
2) Program to find maximum sum of elements in an array - sujithforu.blogspot.com/2012/11/program-to-find-maximum-sum-of-elements.html

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++