Skip to content

Instantly share code, notes, and snippets.

@jkxyz
Created May 29, 2015 22:42
Show Gist options
  • Save jkxyz/9a7bf3f42da309721fff to your computer and use it in GitHub Desktop.
Save jkxyz/9a7bf3f42da309721fff to your computer and use it in GitHub Desktop.
Calculate continuous periods in a sorted list of periods
-module(periods).
-export([get_periods/1, dummy_data/0]).
%% Dummy data for demonstration purposes
dummy_data() -> [{1, 3}, {2, 10}, {10, 11}, {20, 23}, {21, 23}, {21, 23}, {50, 51}].
%% Returns a list of continuous periods within a sorted list of periods
%% i.e. [{1,4},{3,5},{6,7}] -> [{6,7},{1,5}]
%% This was largely written to demonstrate how to solve a problem functionally to my boyfriend
get_periods(Periods, Period, []) ->
[Period | Periods];
get_periods(Periods, null, [Period | Tail]) ->
get_periods(Periods, Period, Tail);
get_periods(Periods, {PeriodStart, PeriodEnd}, [{Start, End} | Tail]) when Start =< PeriodEnd ->
get_periods(Periods, {PeriodStart, End}, Tail);
get_periods(Periods, CurPeriod, Remaining) ->
get_periods([CurPeriod | Periods], null, Remaining).
get_periods(Data) ->
get_periods([], null, Data).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment