Wednesday, January 14, 2009

Sequence grouping logic using .NET?

This post is to build a windows application using C#.NET

The necessity of this application is as follows.

Input:-

A text file which has data as follows
1,6,3,5,8,31,43,10,44,13,44,12,66,45,11,32,40,45,43,44,60,2,67

Output:-
I need to sort all these values and then group the numbers on sequence basis as
1 - 3, 5 - 6,8,10 - 13, 31 - 32, 40, 43 - 45, 60, 66 - 67

These lines of code are to open an “open file dialog” box to browse and open text file that has the above input data.

I am creating a simple windows form that has only one button to open “open file dialog” box.



Code:-
//Open file dialog
opnFldg.ShowDialog();
//Get selected file path from file dialog and assigne to variable
string strFile = opnFldg.FileName;
//If file is selected with out cancelling the save dialog
if (strFile.Trim().Length > 0)
{
//Initialise string builder to append each string
StringBuilder objBuilder = new StringBuilder();
//Read all the data avialble in the text file
string strData = File.ReadAllText(strFile);
//Spilt the data available in the text file based on comma's
//to get exact numbers
string[] strNums = strData.Split(new char[1] { ',' });
//Convert the string values to number so, that sort can be done and
//differences of consecutive can be calculated to create sequenec string
int[] intNums = new int[strNums.Length];
for (int i = 0; i < strNums.Length; i++)
intNums[i] = Convert.ToInt32(strNums[i]);
//sort the number array
Array.Sort(intNums);
int intPrevNum = 0;
//Loop through each item in the sorted number array
for (int i = 0; i < intNums.Length; i++)
{
if (i == 0)
{
//If it is first item append directly
objBuilder.Append(intNums[i]);
}
//If consecutive number difference is greater than or equal to 2
else if (intNums[i] - intNums[i - 1] >= 2)
{
//If top number from previous sequences is not equal to
//previous number then append '-' to say that there to and from sequence
if (intPrevNum != intNums[i - 1])
objBuilder.Append(" - " + intNums[i - 1]);
//Appaned ',' and new number to start new sequenece
objBuilder.Append(" ,"+intNums[i]);
//Assign the current sequence header or top to previous number
intPrevNum = intNums[i];
}
//If it is last number and also if the difference between previous number and
//curretn number is not greater than or equal to 2 then append '-'
else if (i == intNums.Length - 1)
{
objBuilder.Append(" - " + intNums[i]);
}
}
//Display message box of the created string
MessageBox.Show(objBuilder.ToString());
}
Output:-













No comments: