다음과 같은 방법으로 매우 만족합니다. 열거 형 및 정렬 된 분리 된 범위의 목록을 사용하고 범위에없는 항목을 건너 뜁니다. 범위가 null 인 경우 모든 항목을 그냥 걷습니다. 열거 가능 영역과 범위 목록은 모두 커질 수 있습니다. 이 방법은 가능한 한 높은 성능을 원합니다.누군가이 열거 자의 더 나은 버전을 생각해 낼 수 있습니까?
누가 좀 더 우아한 코드를 생각해 낼 수 있습니까? 나는 주로 C# 구현에 관심이 있지만 누군가가 3 글자로 APL을 구현했다면 멋지다. 나는 내 앞에 내 Windows PC가없는
public static IEnumerable<T> WalkRanges<T>(IEnumerable<T> source, List<Pair<int, int>> ranges)
{
if(ranges == null)
return null;
return source.Where((item, index) => ranges.Any(y => y.First < index && y.Second > index)).AsEnumerable();
}
그리고 내가 제대로 코드를 이해 모르겠지만, 시도 :
public static IEnumerable<T> WalkRanges<T>(IEnumerable<T> source, List<Pair<int, int>> ranges)
{
Debug.Assert(ranges == null || ranges.Count > 0);
int currentItem = 0;
Pair<int, int> currentRange = new Pair<int, int>();
int currentRangeIndex = -1;
bool betweenRanges = false;
if (ranges != null)
{
currentRange = ranges[0];
currentRangeIndex = 0;
betweenRanges = currentRange.First > 0;
}
foreach (T item in source)
{
if (ranges != null) {
if (betweenRanges) {
if (currentItem == currentRange.First)
betweenRanges = false;
else {
currentItem++;
continue;
}
}
}
yield return item;
if (ranges != null) {
if (currentItem == currentRange.Second) {
if (currentRangeIndex == ranges.Count - 1)
break; // We just visited the last item in the ranges
currentRangeIndex = currentRangeIndex + 1;
currentRange = ranges[currentRangeIndex];
betweenRanges = true;
}
}
currentItem++;
}
}
이 코드는 겹치는 범위를 처리하지 않습니다. 주어진 범위 (1,6) (4,8) 우리는 항목 1..8을 가져야하지만 항목 1..6을 가져야합니다. 디자인에 의한 것인가? – Handcraftsman