MathGroup Archive 1996

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

Search the Archive

Re: functional code

  • To: mathgroup at smc.vnet.net
  • Subject: [mg4791] Re: [mg4779] functional code
  • From: Allan Hayes <hay at haystack>
  • Date: Mon, 16 Sep 1996 23:51:19 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

Richard Gaylord<gaylord at ux1.cso.uiuc.edu>
[mg4779] functional code
In response to request for functional code to solve the following

>>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.
>
>Nest[
>Function[y,
>({Join[y[[1]],{#}] , DeleteCases[y[[2]], #]})&[Max[First[y[[2]]],
>Last[y[[2]]]]]], {{}, row}, Length[row]][[1]]


Richard,

(1)
There is a problem if there are repeated entries in row.

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

	First::first: {} has a length of zero and no first element.
	Last::nolast: {} has a length of zero and no last element.
	{1, Max[First[{}], Last[{}]]}
	
(2)
Table gives a fast solution:

row = Table[Random[],{500}];

(res1 =
   Block[{f=1, l = Length[row]},
      Table[If[row[[f]]>row[[l]], row[[f++]], row[[l--]]],{n,l}]
   ]
 );//Timing

	{0.5 Second, Null}	

Compared to your,	
(res2=
   Nest[
      Function[y,
       	({Join[y[[1]],{#}],DeleteCases[y[[2]], #]})&[
 	  Max[First[y[[2]]],Last[y[[2]]]]
	]
      ],
      {{}, row},
      Length[row]
    ][[1]]
);//Timing

	{9.5 Second, Null}


res1 == res2
	
	True
	
Allan Hayes,
hay at haystack.demon.co.uk



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


  • Prev by Date: About EPS GRAPHIC'S FORMAT
  • Next by Date: Contours in a spherical projection
  • Previous by thread: functional code
  • Next by thread: Re: functional code