Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't figure out how to do an simple algoritm to get the sum of two numbers

I am trying to find a solution to the problem "Two Sum" if you recognize it , and I’ve run into a problem and I cannot figure it out (Lua)

Code:

num = {2,7,11,15}
target = 9
current = 0 
repeat
  createNum1 = tonumber(num[math.random(1,#num)])
  createNum2 = tonumber(num[math.random(1,#num)])
  current = createNum1 + createNum2
until current == target
  print(table.find(num,createNum1), table.find(num,createNum2)) 

Error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lua5.3: HelloWorld.lua:9: attempt to call a nil value (field 'find')
stack traceback:
    HelloWorld.lua:9: in main chunk
    [C]: in ?

Thank you!

>Solution :

Lua has no table.find function in its very small standard library; just take a look at the reference manual.

You could implement your own table.find function, but that would just be monkey-patching an overall broken algorithm. There is no need to use a probabilistic algorithm that probably runs in at least quadratic time if there only is one pair of numbers that adds up to the desired number. Instead, you should leverage Lua’s tables – associative arrays – here. First build an index of [number] = last index:

local num = {2,7,11,15}
local target = 9

local idx = {}
for i, n in ipairs(num) do idx[n] = i end

then loop over the numbers; given a number m you just need to look for target - m in your idx lookup:

for i, n in ipairs(num) do local j = idx[target - n]; if j then print(i, j) break end end

if you want to exit early – sometimes without building the full idx table – you can fuse the two loops:

local idx = {}
for i, n in ipairs(num) do
    local j = idx[target - n]
    if j then
        print(j, i)
        break
    end
    idx[n] = i
end

other solutions exist (e.g. using sorting, which requires no auxiliary space), but this one is elegant in that it runs in O(n) time & O(n) space to produce a solution and leverages Lua’s builtin data structures.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading