using System;
public class Test
{
public static void Main()
{
Console.WriteLine(ConvertToRanges("1,2,3,4,8,9,10,15"));
Console.WriteLine(ConvertToRanges("5,6,7,9,10,11,12,15,16"));
}
public static string ConvertToRanges(string pageNos)
{
string result=string.Empty;
string[] arr1 = pageNos.Split(',');
int[] arr = new int[arr1.Length];
for (int x = 0; x < arr1.Length; x++) // Convert string array to integer array
{
arr[x] = Convert.ToInt32(arr1[x].ToString());
}
int start,end; // track start and end
end = start = arr[0];
for (int i = 1; i < arr.Length; i++)
{
// as long as entries are consecutive, move end forward
if (arr[i] == (arr[i - 1] + 1))
{
end = arr[i];
}
else
{
// when no longer consecutive, add group to result
// depending on whether start=end (single item) or not
if (start == end)
result += start + ",";
else
result += start + "-" + end + ",";
start = end = arr[i];
}
}
// handle the final group
if (start == end)
result += start;
else
result += start + "-" + end;
return result;
}
}
dXNpbmcgU3lzdGVtOwoKcHVibGljIGNsYXNzIFRlc3QKewogICAgcHVibGljIHN0YXRpYyB2b2lkIE1haW4oKQogICAgewogICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKENvbnZlcnRUb1JhbmdlcygiMSwyLDMsNCw4LDksMTAsMTUiKSk7CiAgICAJQ29uc29sZS5Xcml0ZUxpbmUoQ29udmVydFRvUmFuZ2VzKCI1LDYsNyw5LDEwLDExLDEyLDE1LDE2IikpOwogICAgfQogICAgCQogICAgcHVibGljIHN0YXRpYyBzdHJpbmcgQ29udmVydFRvUmFuZ2VzKHN0cmluZyBwYWdlTm9zKQogICAgewogICAgCXN0cmluZyByZXN1bHQ9c3RyaW5nLkVtcHR5OwogICAgCXN0cmluZ1tdIGFycjEgPSBwYWdlTm9zLlNwbGl0KCcsJyk7CiAgICAJaW50W10gYXJyID0gbmV3IGludFthcnIxLkxlbmd0aF07CiAgICAJCiAgICAJZm9yIChpbnQgeCA9IDA7IHggPCBhcnIxLkxlbmd0aDsgeCsrKSAvLyBDb252ZXJ0IHN0cmluZyBhcnJheSB0byBpbnRlZ2VyIGFycmF5C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