Path: csiph.com!usenet.blueworldhosting.com!feeder01.blueworldhosting.com!feeder.erje.net!1.eu.feeder.erje.net!weretis.net!feeder4.news.weretis.net!news.mixmin.net!aioe.org!.POSTED!not-for-mail From: Kaz Kylheku Newsgroups: comp.programming Subject: Re: Rotation Date: Tue, 5 Jan 2016 04:59:15 +0000 (UTC) Organization: Aioe.org NNTP Server Lines: 69 Message-ID: <20160104205905.491@kylheku.com> References: NNTP-Posting-Host: OGJi3KNpFOhM58UHZwXj0w.user.gioia.aioe.org X-Complaints-To: abuse@aioe.org User-Agent: slrn/pre1.0.0-18 (Linux) X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.programming:6198 On 2016-01-05, BartC wrote: > On 04/01/2016 17:25, Paul wrote: >> Suppose we want to rotate the list of numbers [1, 2, 3, 4, ..., 10] >> so that it begins with a 4 and we end up with [4,...10, 1, 2, 3]. >> >> I was looking at the standard-library c++ way to do this from >> http://www.cplusplus.com/reference/algorithm/rotate/ >> >> There we get (as an example) the code below. To rotate as above, >> middle would be the pointer to 4 which is indexed 3 in c++ which >> begins counting at zero. >> >> template >> void rotate (ForwardIterator first, ForwardIterator middle, >> ForwardIterator last) >> { >> ForwardIterator next = middle; >> while (first!=next) >> { >> swap (*first++,*next++); >> if (next==last) next=middle; >> else if (first==middle) middle=next; >> } >> } >> >> >> I can verify that this code works for special cases but it's not >> intuitively clear that it should always work. > > It's easy enough to test. I'm not familiar with C++ so I tried this > somewhat different language, doing an in-place left-rotation of the > caller's data: > > proc rotate(&a,middle)= > first := a.lwb > last := a.upb+1 > next := middle > > while first <> next do > swap(a[first++], a[next++]) > if next = last then > next := middle > elsif first = middle then > middle := next > fi > od > end Lol, blub languages. $ ./txr This is the TXR Lisp interactive listener of TXR 129. Use the :quit command or type Ctrl-D on empty line to exit. 1> (defparm a (range 0 9)) a 2> (defparm b (range 0 9)) b 3> a (0 1 2 3 4 5 6 7 8 9) 4> b (0 1 2 3 4 5 6 7 8 9) 5> (rotate [a 0..8] [a 8..:]) (0 1 2 3 4 5 6 7) 6> (rotate [b 0..2] [b 2..:]) (0 1) 7> a (8 9 0 1 2 3 4 5 6 7) 8> b (2 3 4 5 6 7 8 9 0 1)