Ich habe Liste von ganzen Zahlen wie {1,2,3,5,8,9,10}, ich brauche das folgende Ergebnis [1,3], [5,5], [8,10]Wie finde ich ein fortlaufendes Segmentpaar in einer gegebenen Liste von ganzen Zahlen (funktional nicht imperativ)?
Ich habe die Lösung im imperativen Stil geschrieben, aber ich möchte eine Lösung, die mit der funktionalen Programmierung übereinstimmt.
Meine Imperativ Lösung:
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;
}
Was hinter den Regeln der Umwandlung von {1,2,3,5,8,9,10} zum Ergebnis "[1,3], [5,5], [8,10]"? –
@DavidArno Es sieht so aus, als wären Bereiche basierend auf fortlaufenden Nummern nicht mehr als 1 größer als die vorherigen Zahlen in der geordneten Liste. – juharr
@DavidArno Es ist eine Liste von Bereichen aufeinanderfolgender Ganzzahlen. – Luaan