Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Go from end to start of array
Date: Fri, 20 Feb 2009 03:41:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 53
Message-ID: <gnl8od$4jk$1@fred.mathworks.com>
References: <15173892.1234517269163.JavaMail.jakarta@nitrogen.mathforum.org> <24575660.1235063653276.JavaMail.jakarta@nitrogen.mathforum.org>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1235101261 4724 172.30.248.35 (20 Feb 2009 03:41:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 20 Feb 2009 03:41:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:519596

Arthur <artnaz@gmail.com> wrote in message <24575660.1235063653276.JavaMail.jakarta@nitrogen.mathforum.org>...
> Sorry, I made a mistake. You have to start with deleting the first element. So the example will be:
> 
> [ 1 2 3 4 5 6 7 8 9 10 ] 
> [ 2 3 4 5 6 7 8 9 10 ] 
> [ 2 3 4 6 7 8 9 10 ]
> [ 2 3 4 6 7 8 10 ]
> [ 2 3 6 7 8 10 ]
> [ 2 3 6 7 8 ]
> [ 2 3 6 8 ]
> [ 2 3 8 ]
> [ 2 3 ]
> [ 2 ] 
> 
> This is what I got, where
> 
> N=amount of balls = input
> M=balls to be skipped = input
> 
> >m=M;
> >a = [2:N]; %we start with the second element since the first must be deleted anyway
> >while length(a)>1
> >    a(M+1)=[];
> >    M=mod(M+m,length(a+1));
> >end
> >a %=output
> 
> The last thing I have to do is to create a second part where M>N.
> 
> So I think this should be it. If there are any comments or tips to save work or make the script better/faster, I would gladly hear them.

  If the final value of 'a' is the only output you are seeking, and if you wish to do this for large n - the initial length of 'a' - say 50 or more, the following code is an alternative method of doing your calculations which is faster, though for small n it may be slower.  For n in the thousands it is dramatically faster, since it is an order log(n) algorithm.  'm' is the length of skip taken in vector 'a' and may be larger than n if desired.

if m == 1
 a = n;
else
 a = 1;
 k = 1;
 while k < n
  c = ceil((k-a+1)/(m-1));
  if c <= n-k
   k = k + c;
   a = mod(a+m*c-2,k-1)+2;
  else
   a = a + m*(n-k);
   k = n;
  end
 end
end

  I am hoping you won't ask me for the theory behind this algorithm.  It would be rather troublesome for me to have to explain it.

Roger Stafford