私は{1,2,3,5,8,9,10}のような整数のリストを持っていますので、次の結果が必要です [1,3]、[5,5]、[8,10]与えられた整数リスト(連続したセグメント)をどのように見つけるか?
私は命令的なスタイルを使用して解決策を書いたが、私は関数型プログラミングに対応した解決策が必要だ。
マイ不可欠ソリューション:
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;
}
です'{1,2,3,5,8,9,10} 'を結果[1,3]、[5,5]、[8,10]'に変換しますか? –
@DavidArno連続した数字に基づく範囲は、順序付きリストの前の数字より1つ大きくないようです。 – juharr
@DavidArno連続する整数の範囲のリストです。 – Luaan