www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 6621] New: Superimposition amount for std.range.chunks

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=6621

           Summary: Superimposition amount for std.range.chunks
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc



std.range.chunks is quite useful. For it a rather useful third optional
argument (that defaults to 0) is how many items are repeated from the precedent
chunk:

auto data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

chunks(data, 3, 0) ==> (default, as now)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

chunks(data, 3, 1) ==>
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

chunks(data, 3, 2) ==>
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9],
[8, 9, 10]]


In Python I use now and then a lazy generator with such extra argument.

The third argument can't be higher than the second (if they are equal it's like
cycle on a slice).

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Sep 08 2011
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=6621




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: -------
Apr 27 2013