Adjacent number algorithm grouper

前端 未结 13 1691
不思量自难忘°
不思量自难忘° 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:49

    I've rewritten your code like this:

        public static string[] FormatInts(int[] ints)
        {
            Array.Sort<int>(ints);
            List<string> values = new List<string>();
    
            for (int i = 0; i < ints.Length; i++)
            {
                int groupStart = ints[i];
                int groupEnd = groupStart;
                while (i < ints.Length - 1 && ints[i] - ints[i + 1] == -1)
                {
                    groupEnd = ints[i + 1];
                    i++;
                }
                values.Add(string.Format(groupEnd == groupStart ? "{0}":"{0} - {1}", groupStart, groupEnd));
            }
            return values.ToArray();
        }
    

    And then:

    /////////////////
    int[] myInts = { 1,2,3,5,7,9,10,11,12,14 };
    string[] result = FormatInts(myInts); // now result haves "1-3", "5", "7", "9-12", "14"
    
    0 讨论(0)
提交回复
热议问题