Last active
July 4, 2016 14:11
-
-
Save smallgeek/581f285eb183bf8075d308cd60c02467 to your computer and use it in GitHub Desktop.
@gab_km さんと @wonderful_panda さんからの指摘を受け修正したもの。ついでに C# にした
This file contains 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
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