How to Make Sequence set

Posted by Saranpselvam under C# on 9/19/2014 | Points: 10 | Views : 427 | Status : [Member] | Replies : 3
HI

My input = "1,2,3,4,5,7,9,10,11,12"
expected output = "1-5,7,9-12"

one more Input for better understanding



My input = "1,2,3,4,6,7,9,11,12,13"
expected output = "1-4,6-7,9,11-13"

How to perform this?

saranpselvam@gmail.com




Responses

Posted by: Mahesh_Chs on: 9/24/2014 [Member] Starter | Points: 25

Up
0
Down
Hi,

try this

int[] arrint = new int[] { 1, 2, 3, 4, 5, 7, 9, 10, 11, 12 };
List<string> lststring = new List<string>();
int j = arrint[0];
int k = 0;

for (int i = 0; i < arrint.Length; i++)
{
if (arrint[i] != j || i == arrint.Length - 1)
{
j = arrint[i];
if (arrint[k] == arrint[i - 1])
{
lststring.Add(arrint[k].ToString());
}
else
{
if (i == arrint.Length - 1)
{
lststring.Add(arrint[k] + "-" + arrint[i]);
}
else
lststring.Add(arrint[k] + "-" + arrint[i - 1]);
}
k = i;
}
j++;

}
foreach (string item in lststring)
{
Console.WriteLine(item);
}


let me know if you have any issues

Saranpselvam, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Naveenhcl on: 9/24/2014 [Member] Starter | Points: 25

Up
0
Down
Hi,

On what basis you separate numbers with that range can you please elaborate it little bit.

Saranpselvam, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Mahesh_Chs on: 9/24/2014 [Member] Starter | Points: 25

Up
0
Down
Here i am taking starting value into j and in the last i have increment the value of j by 1(j++)
so now the j value will be continuous value like(1,2,3,....)

now i am checking that continuous value(j) with arrint[i]

if the condition is true than doing nothing, if the continuity is disturbed than i am taking the starting value and ending value like in expected output as shown below into the list

if (i == arrint.Length - 1)
{
lststring.Add(arrint[k] + "-" + arrint[i]);
}
else
lststring.Add(arrint[k] + "-" + arrint[i - 1]);
}

here k is used to remember the starting location, where the new continuity is started

Saranpselvam, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response