Adjacent number algorithm grouper

前端 未结 13 1743
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  遇见更好的自我
    2021-02-15 07:26

    I'm a bit late to the party, but anyway, here is my version using Linq:

    public static string[] FormatInts(IEnumerable ints)
    {
     var intGroups = ints
      .OrderBy(i => i)
      .Aggregate(new List>(), (acc, i) =>
      {
       if (acc.Count > 0 && acc.Last().Last() == i - 1) acc.Last().Add(i);
       else acc.Add(new List { i });
    
       return acc;
      });
    
     return intGroups
      .Select(g => g.First().ToString() + (g.Count == 1 ? "" : "-" + g.Last().ToString()))
      .ToArray();
    }
    

提交回复
热议问题