Mohanraja Mohanraja - 3 months ago 6
C# Question

How to find continuous segment pair in given list of integers (Functionally not imerative)?

I have List of integers like {1,2,3,5,8,9,10}, I need the following result
[1,3],[5,5],[8,10]

I written the solution using imperative style, but I want a solution which align with functional programming.

My imperative solution:

public static List<ContinuousNotificationSegment> ConvertToNotificationSegment(this List<NotificationDTO> input)
{
var sortedNotificationList = input.Select(n => n.ID).ToList();
sortedNotificationList = sortedNotificationList.OrderBy(n => n).ToList();
List<ContinuousNotificationSegment> continuousSegments = new List<ContinuousNotificationSegment>();

long continuousSegmentStart = 0, continuousSegmentEnd = 0;

for (int i = 0; i < sortedNotificationList.Count; i++)
{
if (IsContinuous(sortedNotificationList[i], ((i + 1) < sortedNotificationList.Count ? sortedNotificationList[i + 1] : -999)))
{
continuousSegmentStart = continuousSegmentStart == 0 ? sortedNotificationList[i] : continuousSegmentStart;
}
else
{
continuousSegmentEnd = sortedNotificationList[i];

continuousSegments.Add(new ContinuousNotificationSegment
{
MinNotificationId = continuousSegmentStart == 0 ? continuousSegmentEnd : continuousSegmentStart,
MaxNotificationId = continuousSegmentEnd
});

continuousSegmentStart = 0;
}
}

return continuousSegments;
}

private static bool IsContinuous(long prevValue, long nextValue)
{
return nextValue - prevValue == 1;
}

Answer
var input = new[] { 1, 2, 3, 5, 8, 9, 10 };

var result =
    input
        .Skip(1)
        .Aggregate(
            input.Take(1).Select(x => new { start = x, end = x }).ToList(),
            (a, x) =>
            {
                var last = a.Last();
                if (last.end + 1 == x)
                {
                    a[a.Count - 1] = new { start = last.start, end = x };
                }
                else
                {
                    a.Add(new { start = x, end = x });
                }
                return a;
            });

That works. I get:

result

Comments