By which I suggest this:
Given the input set of numbers:
1,2,three,four,5 turns into "1-5".
1,two,3,five,7,nine,ten,
Buy Office 2007 Key,eleven,12,14 becomes "1-3, five,
Microsoft Office 2010 Standard Key, 7,
Office Home And Student 2010 Key, 9-12, 14"
This will be the very best I managed to come up with: [C#]
Which feels just a little sloppy to me, so the issue is, is there in some way a lot more readable and/or elegant answer to this?
public static string[] FormatInts(int[] ints)
{ if (ints == null) throw new ArgumentNullException("ints"); // hey what are you doing? if (ints.Length == 0) return new string[] ""; // absolutely nothing to process if (ints.Duration == one) return new string[] ints[0].ToString(); // nothing at all to method Array.Sort<int>(ints); // need to kind these lil' babies List<string> values = new List<string>(); int lastNumber = ints[0]; // start with the first number int firstNumber = ints[0]; // same as above for (int i = one; i < ints.Length; i++) { int current = ints[i]; int difference = (lastNumber - current ); // compute difference between last number and current number if (difference == -1) // the numbers are adjacent { if (firstNumber == 0) // this is the first of the adjacent numbers firstNumber = lastNumber; else // we're somehow in the middle or at the end of the adjacent number set lastNumber = current; continue; } else { if (firstNumber > 0 && firstNumber != lastNumber) // get ready to print a set of numbers { values.Add(string.Format("0-1",
PC Connection, Inc. - Overview, firstNumber, lastNumber)); firstNumber = 0; // reset } else // print a single value { values.Add(string.Format("0",
Office 2010 Professional X86, lastNumber)); } } lastNumber = current; } if (firstNumber > 0) // if theres anything left, print it out { values.Add(string.Format("0-1", firstNumber,
Windows 7 Ultimate Sale, lastNumber)); } return values.ToArray();
}