On Friday, 16 October 2015 at 11:11:28 UTC, Guillaume Chatelet wrote:
Is there an idiomatic way to do:

int[] numbers = [0, 1, 2, 3];
assert(adjacent_diff(numbers) == [1, 1, 1]);

I can't find something useful in the std library.

import std.range, std.algorithm;

auto slidingWindow(R)(R r, size_t n)
if(isForwardRange!R)
{
        //you could definitely do this with less overhead
        return roundRobin(r.chunks(n), r.save.drop(1).chunks(n))
                .filter!(p => p.length == n);
}

auto adjacentDiff(R)(R r)
{
        return r.slidingWindow(2).map!"a[1] - a[0]";
}

unittest
{
        import std.stdio;
        int[] numbers = [0, 1, 2, 3];
        writeln(numbers.slidingWindow(2));
        writeln(adjacentDiff(numbers));
        assert(adjacentDiff(numbers).equal([1, 1, 1]));
}

Reply via email to