MathGroup Archive 1998

[Date Index] [Thread Index] [Author Index]

Search the Archive

FixedPoint and SameTest




i recieved the following question and thought i'd post an answer here
for others who might want to do the same sort of thing.


>     What is a simple procedure that works like NestList but stops 
>once an element in the list repeats.
>
>I want something like FixedPointList, except that instead of stopping
>when two consecutive outputs are the same, it would stop when it 
>generates an element it has generated earlier.

here it is, shown for a simple example a function that picks a random
integer between 1 and (the last random integer generated + 4):

In[39]:=
SeedRandom[88]
FixedPointList[Random[Integer, {1, # + 4}]&, 5 ]

Out[40]=
{5,4,2,4,6,3,5,2,3,1,5,3,1,5,5}

In[41]:=
SeedRandom[88]
lis = {};
FixedPointList[(AppendTo[lis, #]; Random[Integer, {1, # + 4}] )&, 5,    
                        SameTest -> (MemberQ[lis, #2] == MemberQ[lis,
#1] &) ]

Out[43]=
{5,4,2,4}

well, la di da [as anne hall would have said]


note: there is also a recursive function definition which will do this
[see the landMindWalk function definition given in exercise #3 on pp.
217, 219 in Introduction to Progrmaming with Mathemaitca 2nd Edition by
Gaylord, Welllin and Kamin]. personally i prefer the code given here as
thinking recursively gives me a severe headache.

-- 
richard j. gaylord, university of illinois, gaylord@uiuc.edu



  • Prev by Date: Re: Stack graphics
  • Next by Date: A stupid question...
  • Prev by thread: Re: Animation?
  • Next by thread: Re: FixedPoint and SameTest