I’m trying to convert any sorted (ascending) list of positive integers into a string of comma-separated values, including shorthand for “runs” of consecutive numbers more than 2 numbers long. A few examples:
Array( 1, 3, 5, 7, 8, 9 ) = “1,3,5,7-9”
Array( 4, 5, 11, 12, 15, 16, 17 ) = “4,5,11,12,15-17”
Array( 1, 2, 3, 4, 5, 6, 8, 11, 12, 23, 24, 25 ) = “1-6,8,11,12,23-25”
The string without runs is obviously very easy. Here’s my code that doesn’t work. It started out simply and I kept piling on more things. It’s obviously wrong logic, but I’m having trouble thinking in another way. Any help?
// a sorted integer array i() is given
' go through and remove indexes within a run
' look at 2 at a time and don't mark runs that are only 2 numbers long
dim j, n, thisA, thisB, lastValue as integer
dim r(), final as string
r.append str( i(0) )
lastValue = i(0)
j = 1
while j < i.Ubound
thisA = i(j)
thisB = i(j+1)
if thisA = lastValue + 1 and thisB = lastValue + 2 then
// RUN OF 2
if j = i.Ubound - 1 then
r.append "-"
r.append str( thisB )
else
r.append "-"
lastValue = thisB
end if
j = j + 2
elseif thisA = lastValue + 1 then
// RUN OF 1
if j = i.Ubound - 1 then
r.append str( thisA )
r.append str( thisB )
else
r.append str( thisA )
lastValue = thisA
end if
j = j + 1
else
// NO RUN
if j = i.Ubound - 1 then
r.append str( thisA )
r.append str( thisB )
else
r.append str( thisA )
lastValue = thisA
end if
j = j + 1
end if
wend
' always append the last value of an odd array (wrong)
if j = i.Ubound then r.append str( i(j) )
' horrible
final = ReplaceAll( join( r(), "," ), "-,-", "-" )
while instr( final, "-,-" ) > 0
final = ReplaceAll( final, "-,-", "-" )
wend
final = ReplaceAll( final, ",-,", "-" )
return final