There is a certain array of numbers, approx. [1,2,3,4,6,7,12,14,15,16] It is necessary to convert it to a string of type "1-4,6,7,12,14-16"

How to do it?

  • one
    What did you manage to do in a couple of hours? In which direction and how far has your thought advanced? - Bulson
  • one
    Take a look at this my question and answer @Grundy, if you think a little, I think you can achieve the result you need - Bald
  • The inverse problem: stackoverflow.com/q/778367/218063 - Andrew NOP
  • one
    Possible duplicate question: Group consecutive numbers in an array . It only remains to add .Select(list => list.Count == 1 ? $"{list.First()}" : $"{list.First()}-{list.Last()}") and then put in string.Join(",", ...) - Andrew NOP

2 answers 2

Probably, my solution is not very optimized, but something is better than nothing ...

  var intArray = new int[] { 1, 2, 3, 4, 6, 7, 12, 14, 15, 16, 17, 19, 20, 22, 23, 24, 25, 26, 27 }; var orderedArray = intArray.OrderBy(x => x).ToList(); string result = String.Empty; int? lastNum = null; int? fistNum = null; for (int i = 0; i < orderedArray.Count; i++) { var endFlag = i == orderedArray.Count - 1; if (fistNum == null) { result += orderedArray[i].ToString(); fistNum = orderedArray[i]; lastNum = orderedArray[i]; continue; } var flaSequnce = orderedArray[i - 1] == orderedArray[i] - 1; if (flaSequnce) { lastNum = orderedArray[i]; if (!endFlag) continue; } if (!flaSequnce && fistNum != lastNum || endFlag) { string delim = "-"; if (lastNum != null) { delim = fistNum - lastNum == -1 ? "," : "-"; } result += (lastNum != null ? delim + lastNum : "") + (endFlag ? "" : "," + orderedArray[i]); fistNum = orderedArray[i]; lastNum = null; } } 

      var mass = [1,2,3,4,6,7,12,14,15,16,17, 19,20 ,22,23,24,25,26,27]; //int[] function massToStr(mass) { var str = "" + mass[0]; //string var count = 0; //int for(var i = 1 /*int*/; i < mass.length; i++){ if(mass[i] == mass[i-1]+1){ count++; if(i == mass.length-1){ if(count < 2){ str += "," + mass[i]; }else{ str += "-" + mass[i]; } } }else { if(count == 0){ str += "," + mass[i]; }else if(count < 2){ str += ","+ mass[i-1] + "," + mass[i]; }else{ str += "-" + mass[i-1] + "," + mass[i]; } count = 0; } } return str; } console.log(massToStr(mass)); 

    The js code (which was at hand) looks scary and is not optimized, but it works as it should.

    • You can throw this code into the console and it will work. - Denis Podolyachenko
    • This code can easily be rewritten to c #, and instead of minus, I would rewrite to c #. What was at hand helped and that - Denis Podolyachenko
    • sat, wrote, what would a good man minusnul - Denis Podolyachenko
    • c # in this case does not collect the js code, i.e. does not fit the author of the question. If you easily rewrite - why not rewrite before publication? - nick_n_a
    • I did not have a computer with visual studio. And I wanted to help somehow - Denis Podolyachenko