Circular Buffer

Russel Winder russel at winder.org.uk
Wed Feb 12 01:45:54 PST 2014


On Mon, 2014-02-10 at 09:16 +0000, Gary Willoughby wrote:
> On Monday, 10 February 2014 at 03:14:31 UTC, Jonathan Dunlap 
> wrote:
> > (disclaimer: I'm new around here)
> > Is it possible to cycle backwards? If not, what's the best 
> > approach?
> 
> import std.algorithm;
> import std.array;
> import std.range;
> import std.stdio;
> 
> void main(string[] args)
> {
> 	auto data = [1,2,3];
> 
> 	assert(data.cycle.take(5).array       == [1,2,3,1,2]);
> 	assert(data.retro.cycle.take(5).array == [3,2,1,3,2]);
> }


As Gary is aware, I posted this problem to ACCU asking for a C++
version. I think Steve Love has had a go with an added range library not
just pure C++14. I'll post when I have looked at his code, and ensured
it works. He is using Catch for testing so I suspect it will.

I had a quick go at doing a Python 3 version using PyTest:


def provide(sourceSequence, resultLength):
    return (sourceSequence[i % len(sourceSequence)] for i in range(resultLength))

def provideReverse(sourceSequence, resultLength):
    sourceLength = len(sourceSequence)
    return (sourceSequence[sourceLength - 1 - i % sourceLength] for i in range(resultLength))

data = [1, 2, 3]

def test_forward():
    assert tuple(provide(data, 5)) == (1,2,3,1,2)

def test_reverse():
    assert tuple(provideReverse(data, 5)) == (3,2,1,3,2)

-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder



More information about the Digitalmars-d-learn mailing list