fork(15) download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. public static void Main()
  6. {
  7. Console.WriteLine(ConvertToRanges("1,2,3,4,8,9,10,15"));
  8. Console.WriteLine(ConvertToRanges("5,6,7,9,10,11,12,15,16"));
  9. }
  10.  
  11. public static string ConvertToRanges(string pageNos)
  12. {
  13. string result=string.Empty;
  14. string[] arr1 = pageNos.Split(',');
  15. int[] arr = new int[arr1.Length];
  16.  
  17. for (int x = 0; x < arr1.Length; x++) // Convert string array to integer array
  18. {
  19. arr[x] = Convert.ToInt32(arr1[x].ToString());
  20. }
  21.  
  22. int start,end; // track start and end
  23. end = start = arr[0];
  24. for (int i = 1; i < arr.Length; i++)
  25. {
  26. // as long as entries are consecutive, move end forward
  27. if (arr[i] == (arr[i - 1] + 1))
  28. {
  29. end = arr[i];
  30. }
  31. else
  32. {
  33. // when no longer consecutive, add group to result
  34. // depending on whether start=end (single item) or not
  35. if (start == end)
  36. result += start + ",";
  37. else
  38. result += start + "-" + end + ",";
  39.  
  40. start = end = arr[i];
  41. }
  42. }
  43.  
  44. // handle the final group
  45. if (start == end)
  46. result += start;
  47. else
  48. result += start + "-" + end;
  49.  
  50. return result;
  51. }
  52. }
Success #stdin #stdout 0.04s 37016KB
stdin
Standard input is empty
stdout
1-4,8-10,15
5-7,9-12,15-16