我有一個數組數組,我想查找其中第一個連續的升序數字序列(計數多於一個)。C#lambda和數組中的遞增值
例輸入:{5, 1, 2, 4, 8, 7, 6, 9}
所需的輸出:{1, 2, 4, 8}
我有一個數組數組,我想查找其中第一個連續的升序數字序列(計數多於一個)。C#lambda和數組中的遞增值
例輸入:{5, 1, 2, 4, 8, 7, 6, 9}
所需的輸出:{1, 2, 4, 8}
這應該找到一個給定的起始索引第一上升序列:
public static IEnumerable<int> GetAscending(IEnumerable<int> input, int startIndex)
{
var ascending = input.Skip(startIndex)
.Zip(input.Skip(startIndex + 1), (first, second) => new { Num = first, Next = second, Diff = second - first })
.SkipWhile(p => p.Diff <= 0)
.TakeWhile(p => p.Diff > 0)
.Select(p => Tuple.Create(p.Num, p.Next))
.ToArray();
if(ascending.Length == 0) return Enumerable.Empty<int>();
return ascending.Select(t => t.Item1).Concat(new int[] { ascending.Last().Item2 });
}
@Servy - 謝謝,編輯 – Lee 2012-08-07 19:42:07
public IEnumerable<int> getAscendingValues(IEnumerable<int> source)
{
List<int> output = new List<int>();
foreach (int next in source)
{
if (output.Count == 0 || output.Last() < next)
{
output.Add(next);
}
else
{
if (output.Count <= 1)
{
output.Clear();
}
else
{
return output;
}
}
}
if (output.Count > 1)
{
return output;
}
else
{
return null; //could also return an empty enumeration
}
}
如果你想在一個特定的指數,開始你可以調用這個,而不是增加一個額外的參數,以支持它之前使用Skip
方法。 (即getAscendingValues(values.Skip(startIndex))
)
你的意思是隻返回_longest_遞增序列? – twoflower 2012-08-07 18:59:36
你會找到最長的子序列嗎?或者只是任何? – 2012-08-07 19:00:03
不,只有第一個,甚至更好 - 第一個開始一個給定的索引:) – Idov 2012-08-07 19:00:11