In my opinion this is hard to solve, anyways for you not?
What I want to do?
How do you find all pairs of an integer array whose sum is equal to a given number.
For example, if the input integer array is {2, 7, 3, 9, 11} and given sum is 10, the output should be {7,3}.
So you may think this looks easy to solve but dont think about it, if you think long then you know that this problem sounds not easy - when you never code something like that.
This is what I have been created so far but it doesnt seem work well, maybe you find the problem or the mistake I did here.
local numbers = {3,6,4,2,1,5,2}
function sumwewant(array, sum)
for i = 1, #array do
local first = array[i]
for j = 1, #array do
local second = numbers[j]
if ((first + second) == sum)then
print(first, second)
end
end
end
end
local d = sumwewant(numbers, 10)
print(d)
This is an interesting and hard question to answer. This is the best I can do.
local function(array,sumWeWant)
for i = 1, #array, do
local first = array[1]
for j = (i + 1), #array do
local second = array(j)
local result = first + second
if result == sumWeWant then
return result
else return end
end
end
end
ServerScriptService.Script:7: attempt to call a table value
local numbers = {3,6,4,2,1,5,2}
local function findarray(array,sumWeWant)
for i = 1, #array do
local first = array[1]
for j = (i + 1), #array do
local second = array(j)
local result = first + second
local d = sumWeWant
if result == result then
return result
else return end
end
end
end
local d = findarray(numbers, 10)
print(d)
local numbers = {3,6,4,2,1,5,2}
local function findarray(array,sumWeWant)
for i = 1, #array do
local first = array[1]
for j = (i + 1), #array do
local second = array[j]
local result = first + second
local de = sumWeWant
if result == de then
return result
else return end
end
end
end
local d = findarray(numbers, 10)
print(d)
Your code works fine. If the issue is that it’s printing nil then change the function to return an array with all the matched number because your function isn’t returning anything
local numbers = {3,6,4,2,1,5,2}
function sumwewant(array, sum)
local matches = {}
for i = 1, #array do
local first = array[i]
for j = 1, #array do
local second = numbers[j]
if ((first + second) == sum)then
table.insert(matches, {first, second})
end
end
end
return matches
end
local d = sumwewant(numbers, 10)
print(d)
That’s because it’s checking the same number twice, in the 2nd loop you should add a check so i ~= j
local numbers = {3,6,4,2,1,5,2}
function sumwewant(array, sum)
local matches = {}
for i = 1, #array do
local first = array[i]
for j = 1, #array do
if i ~= j then
local second = numbers[j]
if ((first + second) == sum)then
table.insert(matches, {first, second})
end
end
end
end
return matches
end
local d = sumwewant(numbers, 10)
print(d)