Last active
August 29, 2015 14:02
-
-
Save bennage/726d3ede6faf351f9f51 to your computer and use it in GitHub Desktop.
is there an Rx method that already does this?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.