Search code examples
recursionpseudocodedate-rangecoalesce

Recursive algorithm for coalescing / collapsing list of dates into ranges


Given a list of dates

12/07/2010
13/07/2010
14/07/2010
15/07/2010
12/08/2010
13/08/2010
14/08/2010
15/08/2010
19/08/2010
20/08/2010
21/08/2010

I'm looking for pointers towards a recursive pseudocode algorithm (which I can translate into a FileMaker custom function) for producing a list of ranges, i.e.

12/07/2010 to 15/07/2010, 12/08/2010 to 15/08/2010, 19/08/2010 to 20/08/2010

The list is presorted and de-duplicated. I've tried starting from both the first value and working forwards, and the last value and working backwards but I just can't seem to get it to work. Having one of those frustrating days... It would be nice if the signature was something like

CollapseDateList( dateList, separator, ellipsis )

:-)


Solution

  • The main routine would look something like this:

    List<String> list  = new ArrayList<String>();
    
    String firstDate   = dateList[0];
    String lastDate    = dateList[0];
    String currentDate = dateList[0];
    
    for (int i = 1; i < dateList.length(); i++) {
        if (dateDiff(dateList[i], currentDate) == 1) {
            lastDate   = dateList[i];
        } else {
            list.add(firstDate + separator + lastDate);
            firstDate = dateList[i];
            lastDate  = dateList[i];
        }
        currentDate = dateList[i];
    }
    list.add(firstDate + separator + lastDate);
    

    I'm assuming you have some function that tells you if two dates are consecutive or not.