[Issue 6621] Superimposition amount for std.range.chunks
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sat Apr 27 08:51:30 PDT 2013
http://d.puremagic.com/issues/show_bug.cgi?id=6621
--- Comment #1 from bearophile_hugs at eml.cc 2013-04-27 08:51:29 PDT ---
A simple use case, count the number of local maxima in an array (a number is a
local maxima if it is greater than the number before and after it):
size_t countMaxima(T)(in T[] xs) pure nothrow
if (__traits(compiles, T.init > T.init)) {
if (xs.length < 2)
return xs.length;
typeof(return) count = 0;
foreach (immutable i; 1 .. xs.length - 1)
count += xs[i] > xs[i - 1] && xs[i] > xs[i + 1];
return count + (xs[0] > xs[1]) + (xs[$ - 1] > xs[$ - 2]);
}
Using chunks() with the second argument the code avoids some bug-prone indexes
(this is component programming):
size_t countMaxima(T)(in T[] xs) pure nothrow
if (__traits(compiles, T.init > T.init)) {
if (xs.length < 2)
return xs.length;
auto count = xs
.chunks(3, 2)
.filter!(c => c[1] > c[0] && c[1] > c[2])
.walkLength;
return count + (xs[0] > xs[1]) + (xs[$ - 1] > xs[$ - 2]);
}
Another use case:
http://forum.dlang.org/thread/zdhfpftodxnvbpwvklcv@forum.dlang.org
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list