
Patrick B. answered 06/23/19
Math and computer tutor/teacher
You need to use a state machine in order to process the condensed sequence string...
declare a variable called state with the following values:
0 = beginning of the sequences
1 = numbers are out of sequence
2 = looking for next # in the sequence
3 = end of the sequence..
Here's the code:
class Sequence
{
public static void main(String args[])
{
String inbuff = "1,2,3,4,5,6,8,10,11";
//String ibuff = "1,2,3,4,7,8,10,12,13,14,15,16,17,20,21,24,27,28,29,31,32,33,36,37,41";
String outbuff = " ";
String [] tokens = inbuff.split(",");
int lastX = 0;
int state=0; //state = 0 : beginning of the sequence
// state = 1: comma separates numbers out of sequence
// state = 2: waiting for next # in the sequence
// state = 3: ending of the sequence
for (int iLoop=0; iLoop<tokens.length; iLoop++)
{
int x = Integer.parseInt(tokens[iLoop]);
switch (state)
{
case 0:
{
outbuff = outbuff + x ;
state=2;
break;
}
case 1:
{
if ((x-lastX)==1)
{
outbuff = outbuff + "-" + x;
}
else
{
outbuff = outbuff + "," + x;
}
state=2;
break;
}
case 2:
{
if ((x - lastX)==1)
{
}
else
{
outbuff = outbuff + "-" + lastX + "," + x;
state = 1;
}
break;
}
case 3:
{
if ((x-lastX)==1)
{
outbuff = outbuff + "-";
}
else
{
outbuff = outbuff + ",";
}
outbuff = outbuff + x;
break;
}
}//switch
lastX = x;
if (iLoop==tokens.length-2)
{
state=3;
}
} //for loop
System.out.println(outbuff);
} //main
}