I have a task to find the most bigger increasing succession in Array List.
So if I had array 1 5 1 2 3 1 2
The output must be 1 2 3
Please help me with this task.
Can I write this using linq?
I have a task to find the most bigger increasing succession in Array List.
So if I had array 1 5 1 2 3 1 2
The output must be 1 2 3
Please help me with this task.
Can I write this using linq?
As this is a homework question, I won't give you a complete solution, but here are some hints:
You need to iterate over the numbers and keep track of two things:
The length of the current increasing sequence (initially 0) and the last number of the sequence (initially -1 if the numbers are positive). For example, after iterating over 1 and 5, the two values will be 2 (length) and 5 (last number).
The length of the best sequence found so far - e.g. if you're at the end of your example, the current sequence has length 2 (last two numbers are 1 and 2), but you previously found sequence with length 3.
You can solve this using LINQ - you can write iterations that keep current state using the Aggregate extension method. However, writing this using for loop will be probably easier (especially if you're learning)
Yes, you can do this using linq but code is not very readable. Use loops for more clearly code.
var ind = 0;
var result = ar.Select((i, index) => index > 0 ? new { Val = ar[index], ValIndex = ar[index] > ar[index - 1] ? ind : ++ind } : new { Val = ar[index], ValIndex = 0 }).GroupBy(t => t.ValIndex).Select(x => new { GroupKey = x.Key, Group = x }).OrderByDescending(g => g.Group.Count()).First();
foreach (var r in result.Group)
{
Console.WriteLine(r.Val);
}
You can write a method like that:
IList<T> GetLongestIncreasingSequence<T>(IEnumerable<T> source)
{
var comparer = Comparer<T>.Default;
List<T> longest = null;
List<T> tmp = new List<T>();
T previous = default(T);
bool first = true;
foreach (var item in source)
{
if (first || comparer.Compare(item, previous) > 0)
{
tmp.Add(item);
}
else
{
if (tmp.Any() && (longest == null || longest.Count < tmp.Count))
{
longest = tmp;
}
tmp = new List<T>();
tmp.Add(item);
}
first = false;
previous = item;
}
if (tmp.Any() && (longest == null || longest.Count < tmp.Count))
{
longest = tmp;
}
return longest;
}
Usage:
int[] values = { 1, 5, 1, 2, 3, 1, 2 };
var longest = GetLongestIncreasingSequence(values);
It's not a Linq solution, but I don't think there is a convenient way to do it with Linq...