Table of Contents:

This question revolves around printing a formatted string based on an inputted series of integers, such that it appears like a table of contents.

The Requirements

Given an ordered array of unique, non-zero, positive integers for input, print out a table of contents as per the following rules:

Sequential runs of numbers should be compressed to a dash, such that 1,2,3,4,5 is reduced to "1-5"

Non-sequential numbers should be seperated by a comma, such that 1,2,3,4,7,8,9,12,15 would print as "1-4,7-9,12,15"

Provided is a set of data to test with.

My Experience

In this question, I had access to a computer with visual studio, which was projecting for the room. There was only one person with me there.

First I created some unit tests, inserting all the expectations for the output into the tests. Fine and good, the function would simply return a string. I wrote up an iterator to visit all the numbers in the array, and started checking the states of the values.

What came next involved attempting about 15 different ideas in a jumbled mess of nervous confusion and total and complete brain-drain. Suffice it to say the interviewer wrote up a flowchart for me, but I was unable to transpose that into the application.

I think the biggest problem came from not giving the problem enough time to percolate and diving in too quickly. I thought I had a plan, which was sufficient - but once I had stumbled a few times I didn't recover my footing enough to back away and start fresh. Once neck-deep in words and ideas, the code was just a swirling mess of tension. I also should have avoided scheduling an interview over lunch, since I found myself walking out starving.
One big takeaway: If you are asked if you need a break prior to starting the code, take it, even if you don't feel you need it.

Input values:

uninitialized:null
uninitialized:null
uninitialized:null
uninitialized:null
uninitialized:null
uninitialized:null
uninitialized:null
public static string getOutput(params int[] chapters)
{
   string output = "";
   for(int index = 0; index < chapters.Length; index++)
   {
     //gather data about surroundings 
     bool first = index == 0;
     bool last = index + 1 == chapters.Length;
     bool previousIsSequence = !first && chapters[index - 1] == chapters[index] - 1;
     bool nextIsSequence = !last && chapters[index + 1] == chapters[index] + 1;
     bool printChar = first || last || !nextIsSequence || !previousIsSequence;
     if(printChar)
     {
       // we are printing something - do we need a comma or dash? 
       if(previousIsSequence)
       {
         output += "-";
       }
       else if(!first)
       {
         output += ",";
       }
       //actually write the current number 
       output += chapters[index];
     }
   }
   return output;
}