FixedPoint and SameTest
- To: mathgroup@smc.vnet.net
- Subject: [mg11738] FixedPoint and SameTest
- From: gaylord@ux1.cso.uiuc.edu (richard j. gaylord)
- Date: Thu, 26 Mar 1998 03:09:05 -0500
- Organization: university of illinois
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