Skip to content

Instantly share code, notes, and snippets.

@bennage
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennage/726d3ede6faf351f9f51 to your computer and use it in GitHub Desktop.
Save bennage/726d3ede6faf351f9f51 to your computer and use it in GitHub Desktop.
is there an Rx method that already does this?
namespace RxTest
{
using System;
using System.Collections.Generic;
using System.Linq;
using Chunk = System.Collections.Generic.List<int>;
internal class Program
{
private static void Main(string[] args)
{
var stream = new[] { 10, 11, 12, 0, 1, 10, 11, 12, 13, 14, 15, 2, 4, 6, 7 };
const int detla = 1;
var groups = stream.Aggregate(
new List<Chunk> { new Chunk() },
(chunks, x) =>
{
var lastChunk = chunks.Last();
if (!lastChunk.Any())
{
lastChunk.Add(x);
}
else
{
var lastItem = lastChunk.Last();
if (Math.Abs(lastItem - x) <= detla)
{
lastChunk.Add(x);
}
else
{
var newChunk = new Chunk { x };
chunks.Add(newChunk);
}
}
return chunks;
}).ToList();
groups.ForEach(
chunk =>
{
Console.WriteLine("");
chunk.ForEach(x => Console.Write(x + " "));
});
Console.ReadLine();
}
}
}
@bennage
Copy link
Author

bennage commented Jun 6, 2014

I'm looking for a better way to do this. Some more Rx-ish.

My exact scenario is that I have a stream of messages with timestamps. If a new message occurs within a given timespan since the previous message, I want to group it with that previous message. Otherwise, I start a new group.

Message[] -> Message[][]

In reality, my message group is a class with additional metadata and not just a Message[], but whatevs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment