Simple array question

Alex Tweedly alex at tweedly.net
Fri Oct 1 05:48:48 EDT 2004


At 20:25 30/09/2004 -0700, Mark Brownell wrote:

>What do you get for this? I'm not sure I did this right. [untested]
>
>  repeat for each element i in x
>       put i & return after tResults
>   end repeat
>   put tResults into field 2

I don't see anything in the documentation of "element" or "for each 
element" that assures me they will be taken in the correct order. The docs 
say that each element of the array will have the loop executed for it - but 
says nothing about the order. Since there's a strong parallel with the 
"split"command - which also executes with each element, but explicitly says 
that it operates in hash order not in key-sorted order - I'm not 100% 
confident that this will do what we want every time.

Having said that, it does get the right answer in my one simple test - and 
does it very quickly. [Maybe hash order is the same as key-sorted order for 
the case where the keys are all contiguous integers ?]

I also ran each test 3 or 4 times, and give the range because there was 
more variation than I had expected.

comparable times
Jim's  initial brute force      165 - 172
Mark's faster loop and append    22 -  25
Alex's loop counter and append   12 -  15
Mark's for each element           7 -   8
Franks's sort & line y[i]        20 -  22
Robert's sort & for each         12 -  14

I didn't initially time Frank's suggestion, or Robert's variation on it, 
because they were making the problem harder than it needed to be; they both 
began by
    put the keys of x into y
    sort lines of y
which is unnecessary according to the assumptions of the original question. 
Jim's question gave the method
    repeat for i = 1 to m
        x[i]
and hence we can assume that the keys of the array are contiguous integers; 
given that, there is no requirement to extract and sort the keys.

Of course, if the problem initially posed had been slightly different, then 
these methods might have been required.   And similarly, the scripts from 
both Mark and me used "cr" rather than "the lineDelimiter"; an assumption 
NOT justified by the initial problem statement - but it makes no detectable 
difference to the time.

-- Alex.


More information about the use-livecode mailing list