Does Anyone know how to do this using C#? It's a coding challenge I have for a class.
Q: array of arrays. Group the input integers into sets that are contiguous in the input array.
e.g.
[1, 2, 3, 5, 6, 8, 9, 10] => [ [1, 2, 3], [5, 6], [8, 9, 10] ]
Does Anyone know how to do this using C#? It's a coding challenge I have for a class.
Q: array of arrays. Group the input integers into sets that are contiguous in the input array.
e.g.
[1, 2, 3, 5, 6, 8, 9, 10] => [ [1, 2, 3], [5, 6], [8, 9, 10] ]
Try this:
public IEnumerable<IEnumerable<int>> ConsecutiveGroups(IEnumerable<int> items)
{
bool started = false;
var prev = int.MinValue;
var curSet = new List<int>();
foreach(var item in items.OrderBy(x=>x))
{
if (item != prev + 1 && started)
{
yield return curSet;
curSet = new List<int>();
}
curSet.Add(item);
started = true;
}
yield return curSet;
}
Here is a solution that uses the Segment operator from the MoreLinq library.
using System;
using System.Linq;
using static MoreLinq.Extensions.SegmentExtension;
public class Program
{
public static void Main()
{
int[] source = new[] { 1, 2, 3, 5, 6, 8, 9, 10 };
int[][] result = source
.Segment((current, previous, _) => current != previous + 1)
.Select(segment => segment.ToArray())
.ToArray();
Console.Write($"[{String.Join(", ", source)}]");
Console.Write($" => ");
Console.WriteLine($@"[{String.Join(", ", result
.Select(s => $"[{String.Join(", ", s)}]"))}]");
}
}
Output:
[1, 2, 3, 5, 6, 8, 9, 10] => [[1, 2, 3], [5, 6], [8, 9, 10]]
The Segment extension method has the signature below:
public static IEnumerable<IEnumerable<T>> Segment<T>(
this IEnumerable<T> source,
Func<T, T, int, bool> newSegmentPredicate);