Skip to content

Instantly share code, notes, and snippets.

@smallgeek
Last active July 4, 2016 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smallgeek/581f285eb183bf8075d308cd60c02467 to your computer and use it in GitHub Desktop.
Save smallgeek/581f285eb183bf8075d308cd60c02467 to your computer and use it in GitHub Desktop.
@gab_km さんと @wonderful_panda さんからの指摘を受け修正したもの。ついでに C# にした
public static IEnumerable<IReadOnlyList<T>> ChunkBySumIf<T>(this IEnumerable<T> source, Func<T, double> selector, Func<double, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (selector == null) throw new ArgumentNullException(nameof(selector));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
using (var enumerator = source.GetEnumerator())
{
var values = new List<T>();
var acc = 0.0;
while (enumerator.MoveNext())
{
var x = selector(enumerator.Current);
if (predicate(acc + x))
{
values.Add(enumerator.Current);
acc += x;
}
else
{
yield return values.AsReadOnly();
values = new List<T> { enumerator.Current };
acc = x;
}
}
if (values.Count > 0)
{
yield return values.AsReadOnly();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment