Note that there are some explanatory texts on larger screens.

plurals
  1. POAdjacent number algorithm grouper
    text
    copied!<p>By which I mean this:</p> <p>Given the input set of numbers: </p> <p>1,2,3,4,5 becomes "1-5".</p> <p>1,2,3,5,7,9,10,11,12,14 becomes "1-3, 5, 7, 9-12, 14"</p> <p>This is the best I managed to come up with: [C#]</p> <p><em>Which feels a little sloppy to me, so the question is, is there somehow more readable and/or elegant solution to this?</em></p> <pre><code>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[] { "" }; // nothing to process if (ints.Length == 1) return new string[] { ints[0].ToString() }; // nothing to process Array.Sort&lt;int&gt;(ints); // need to sort these lil' babies List&lt;string&gt; values = new List&lt;string&gt;(); int lastNumber = ints[0]; // start with the first number int firstNumber = ints[0]; // same as above for (int i = 1; i &lt; 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 &gt; 0 &amp;&amp; firstNumber != lastNumber) // get ready to print a set of numbers { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); firstNumber = 0; // reset } else // print a single value { values.Add(string.Format("{0}", lastNumber)); } } lastNumber = current; } if (firstNumber &gt; 0) // if theres anything left, print it out { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); } return values.ToArray(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload