Re: processing a sequence
- From: "William James" <w_a_x_man@xxxxxxxxx>
- Date: Wed, 10 Dec 2008 11:21:17 +0100 (CET)
André Thieme wrote:
joswig@xxxxxxxxxxxxxxxxxxxxxxx schrieb:
(defun collect-sublists (list)
(flet ((collect-sublist ()
(loop for element = (pop list)
while element collect element
while (and list
(<= element (first list))))))
(loop for sublist = (collect-sublist)
while sublist collect sublist)))
"We don't need no stinkin' loops!"
Ruby:
list = [0,1,2,3] * 3
def collect_sublists list, prev=nil, accum=[[]]
return accum if not element = list.first
if prev and element < prev
accum << [element]
else
accum[-1] << element
end
collect_sublists( list[1..-1], element, accum )
end
p collect_sublists( list )
# This could be slower if getting the last element in a list
# is expensive.
def collect_sublists_2 list, accum=[[]]
return accum if not element = list.first
if accum != [[]] and accum[-1][-1] > element
accum << [element]
else
accum[-1] << element
end
collect_sublists_2( list[1..-1], accum )
end
Nearly 15 minutes passed since you posted your solution, and William
James still didn?t show his Ruby one-liner that outperforms the Lisp
solution by a factor of 20 (speedwise). ;-)
André
Ruby is about the slowest "scripting language".
JavaScript is faster.
SpiderMonkey and jslibs:
LoadModule('jsstd')
list = [0,1,2,3,0,1,2,3,1,2,3]
function collect_groups( list, prev, accum )
{ accum = accum || [[]]
var element = list[0]
if ( typeof element == "undefined" )
return accum
if (prev && element < prev)
accum.push( [element] )
else
accum.slice(-1)[0].push( element )
return collect_groups( list.slice(1), element, accum )
}
Print( collect_groups(list).toSource(), '\n')
--- output ---
[[0, 1, 2, 3], [0, 1, 2, 3], [1, 2, 3]]
.
- Follow-Ups:
- Re: processing a sequence
- From: joswig@xxxxxxxxxxxxxxxxxxxxxxx
- Re: processing a sequence
- References:
- processing a sequence
- From: Scott
- Re: processing a sequence
- From: joswig@xxxxxxxxxxxxxxxxxxxxxxx
- Re: processing a sequence
- From: André Thieme
- processing a sequence
- Prev by Date: Re: Coding challenge: Can you make this function more elegant?
- Next by Date: Re: Initializing a (complex rational) array
- Previous by thread: Re: processing a sequence
- Next by thread: Re: processing a sequence
- Index(es):
Relevant Pages
|