MathGroup Archive 1996

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

Search the Archive

functional code

  • To: mathgroup at smc.vnet.net
  • Subject: [mg4779] functional code
  • From: gaylord at ux1.cso.uiuc.edu (richard j. gaylord)
  • Date: Fri, 13 Sep 1996 13:54:58 -0400
  • Organization: university of illinois
  • Sender: owner-wri-mathgroup at wolfram.com

i received the following query from someone and thought i'd post the
problem and a solution i've come up with:

query:

Here is my non-functional solution to this problem:

Given a list of numbers row={18,19,1,11,25,12,22,14}
Select the numbers from the list by taking the largest number
from the ends of the list  until the list is empty.

row={18,19,1,11,25,12,22,14};
p=Length[row];
result={};
Do[If[First[row]>=Last[row],
AppendTo[result, First[row]];row=Rest[row],
AppendTo[result,Last[row]];row=Drop[row,-1]],
{p}];

result

{18,19,14,22,12,25,11,1}
                              
If there a way to do this functionally?

response: yes, of course it can be done functionally.

here's a solution:

[sorry if its a bit crude but i've spent the last 15 months writing
cellular automata programs in mathematica  and there is almost no
programming involved, just simple rule writing, so i may a bit rusty [what
an incrediblly immodest plug for my new book just arriving in bookstores
as of last week  :)].

In[30]:=

Nest[
Function[y, 
({Join[y[[1]],{#}] , DeleteCases[y[[2]], #]})&[Max[First[y[[2]]],
Last[y[[2]]]]]], {{}, row}, Length[row]][[1]]


Out[30]=

{18, 19, 14, 22, 12, 25, 11, 1}


-richard-

-- 
"if you're not programming functionally, then you're programming dysfunctionally"

==== [MESSAGE SEPARATOR] ====


  • Prev by Date: linear congruential generator
  • Next by Date: [Q] ListPlotVectorField[]
  • Previous by thread: linear congruential generator
  • Next by thread: Re: functional code