[REBOL] Re: Sorting
From: joel:neely:fedex at: 17-May-2001 10:33
Hi, Terry,
This is SEVERELY quick and dirty, but here goes...
Terry Brownell wrote:
> Hello...
>
> Here's a exercise...
>
> Sort the following read/lines into N: from shortest length? line
> to longest...
>
> N:[]
>
> one two three "four five six" ; length? = 4
> one two "three four" ; length? = 3
> one two three four five "six seven" ; length? = 6
> one two three four five six "seven eight" ; length? = 7
> one "two three four five" ; length? = 2
>
> Where the string counts as 1.
>
I just hacked a bit at the interactive console, rather than
writing a tidy function. That last bit is "left as an exercise
for the reader"... ;-) (I assumed that the strategy was more
important than the tidy packaging.)
I prefered to determine the "length" once, sort on that, and
then throw away the scaffolding.
>> foo: {one two three "four five six"
{ one two "three four"
{ one two three four five "six seven"
{ one two three four five six "seven eight"
{ one "two three four five"}
Your original data, all as one string
>> boo: parse/all foo "^/"
== [{one two three "four five six"} {one two "three four"}
{one two three four five "six seven"} {one two three four
five six "seve...
The equivalent of READ/LINES (I was too lazy to save it as
a file and read it back in.
>> goo: []
== []
>> foreach hoo boo [
[ append goo reduce [length? parse hoo " " hoo]
[ ]
== [4 {one two three "four five six"} 3 {one two "three four"}
6 {one two three four five "six seven"} 7 {one two three four
five s...
This builds a length/value structure, based on the fact that PARSE
by default leaves quoted substrings intact.
>> sort/skip goo 2
== [2 {one "two three four five"} 3 {one two "three four"}
4 {one two three "four five six"} 6 {one two three four five
"six seven"...
That sorts the pairs by length.
>> boo: []
== []
>> foreach [len val] sort/skip goo 2 [append boo val]
== [{one "two three four five"} {one two "three four"}
{one two three "four five six"} {one two three four five
"six seven"} {one t...
That strips off the lengths, now that we're through using them.
>> foreach hoo boo [print hoo]
one "two three four five"
one two "three four"
one two three "four five six"
one two three four five "six seven"
one two three four five six "seven eight"
The final output...
-jn-