title: Java: Convert int[] to smallest representation as ranges
body: <p>Given an array of int values, how could one parse the series into counting sequence notation?</p>
  
  <p>Examples:</p>
  
  <pre><code>{1, 2, 3, 4, 5, 9, 13, 14, 15} -&gt; "1-5,9,13-15"
  {4, 6, 8, 10, 11, 12, 15, 17}  -&gt; "4,6,8,10-12,15,17"
  </code></pre>
  
  <p>I'm looking for a method that would produce these results. This is what I have so far, but I'm very much stumped at this point:</p>
  
  <p>Test Code:</p>
  
  <pre><code>import java.util.Arrays;
  public class TestSequencing {
      public static void main(String[] args) {
          int[] numbers1 = {1, 2, 3, 4, 5, 9, 13, 14, 15};
          String numbers1s = "1-5,9,13-15";
          System.out.println(Arrays.toString(numbers1));
          System.out.println("Expected:\t" + numbers1s);
          System.out.println("Produced:\t" + sequenceNums(numbers1) + "\n");
  
          int[] numbers2 = {3, 5, 6, 9, 12};
          String numbers2s = "3,5-6,9,12";
          System.out.println(Arrays.toString(numbers2));
          System.out.println("Expected:\t" + numbers2s);
          System.out.println("Produced:\t" + sequenceNums(numbers2) + "\n");
  
          int[] numbers3 = {1, 2, 3, 4, 5, 6, 7};
          String numbers3s = "1-7";
          System.out.println(Arrays.toString(numbers3));
          System.out.println("Expected:\t" + numbers3s);
          System.out.println("Produced:\t" + sequenceNums(numbers3) + "\n");
      }
  
      public static String sequenceNums(int[] nums) {
          StringBuilder sb = new StringBuilder();
          int rangeStart = nums[0];
          int previous = nums[0];
          int current;
          int expected = previous + 1;
  
          for (int i = 1 ; i &lt; nums.length ; i++) {
              current = nums[i];
              expected = previous + 1;               
              if (current != expected || i == (nums.length - 1)) {
                  if (current == rangeStart) {
                      sb.append(previous + ",");
                  } else {
                      sb.append(rangeStart + "-" + previous + ",");
                  }                
                  rangeStart = current;
              }              
              previous = current;
          }
          if (sb.charAt(sb.length() - 1) == ',') {
              sb.deleteCharAt(sb.length() - 1);
          }
          return sb.toString();
      }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>[1, 2, 3, 4, 5, 9, 13, 14, 15]
  Expected:   1-5,9,13-15
  Produced:   1-5,9-9,13-14
  
  [3, 5, 6, 9, 12]
  Expected:   3,5-6,9,12
  Produced:   3-3,5-6,9-9
  
  [1, 2, 3, 4, 5, 6, 7]
  Expected:   1-7
  Produced:   1-6
  </code></pre>