Post Reply 
Little problem(s) July 2022
07-05-2022, 09:41 PM
Post: #12
RE: Little problem(s) July 2022
(07-05-2022 01:56 PM)pier4r Wrote:  Why is POS \(\mathcal{O}(n)\) in userRPL? Is there no direct access to the position in a list, does the system have to iterate through the elements every time? (is DOSUBS the only way to avoid it?)

POS first need to match the object, then return its position.
With unsorted list, linear search is O(n)
Sorted list can use binary search, time complexity O(log(n))

BTW, if the list were sorted, there is no need for POS at all.
We just repeatedly shorten the 2 tails ...

Code:
function f2(lst, x) -- lst sorted, no duplicates
    local i, j = 1, #lst
    while i < j do
        local y = lst[i] + lst[j] - x
        if     y > 0 then j=j-1
        elseif y < 0 then i=i+1
        else print(i, j); i=i+1; j=j-1
        end
    end
end

lua> f2({2,7,11,15}, 17)
1      4
lua> f2({2,5,7,8,10,11,15}, 15)
2      5
3      4
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
Little problem(s) July 2022 - pier4r - 07-04-2022, 06:04 PM
RE: Little problem(s) July 2022 - pauln - 07-05-2022, 01:01 AM
RE: Little problem(s) July 2022 - pier4r - 07-05-2022, 10:00 AM
RE: Little problem(s) July 2022 - pier4r - 07-05-2022, 01:56 PM
RE: Little problem(s) July 2022 - Albert Chan - 07-05-2022 09:41 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 10:51 AM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 12:02 PM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 03:09 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 05:19 PM
RE: Little problem(s) July 2022 - Werner - 07-06-2022, 07:48 AM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 05:27 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 05:37 PM
RE: Little problem(s) July 2022 - pauln - 07-11-2022, 05:34 AM
RE: Little problem(s) July 2022 - pauln - 07-11-2022, 10:32 PM



User(s) browsing this thread: 1 Guest(s)