using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { int[] arr = { 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2 }; Console.WriteLine("arr"); foreach (var intervalo in arr.IntervalosCrescimento()) { Console.WriteLine($"Start {intervalo.Item1}, end {intervalo.Item2}, sinal {intervalo.Item3}"); } int[] arr2 = { 0, 1, 2, 3, 3, 3, 4, 5, 6, -1, -8, 0, 8 }; Console.WriteLine(); Console.WriteLine("arr2"); foreach (var intervalo in arr2.IntervalosCrescimento()) { Console.WriteLine($"Start {intervalo.Item1}, end {intervalo.Item2}, sinal {intervalo.Item3}"); } } } public static class ExtensionMethod { public static IEnumerable> IntervalosCrescimento(this IEnumerable en) where T : IComparable { bool first = true; Tuple result; int start = -1; int end = -1; T previous = default(T); int? previousSign = null; int? sign = null; int index = 0; foreach (T current in en) { if (first) { first = false; start = index; previous = current; } else { sign = current.CompareTo(previous); if (previousSign == null) { previousSign = sign; } else if (previousSign != sign) { end = index; result = Tuple.Create(start, end, previousSign.Value); start = index; previousSign = sign; yield return result; } previous = current; ++index; } } end = index; if (start < end) yield return Tuple.Create(start, end, sign.Value); } }