Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: Re: [mg4779] functional code
Replies: 0  

Advanced Search

Back to Topic List Back to Topic List  
Allan Hayes

Posts: 1,508
Registered: 12/6/04
Re: [mg4779] functional code
Posted: Sep 16, 1996 10:27 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

Richard Gaylord<gaylord@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@haystack.demon.co.uk









Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.