Hey, I’m struggling to come up with a solution to a problem I have been having for a while now. I am attempting to make a function that when given a table of values and a target, returns the values from the table that match the target closest. Here is an example:
local Table = {2, 8, 5, 9, 2, 1, 6, 19}
local function GetTarget(Table, Target, Amount)
—Magic happens here
return NewTable
end
GetTarget(Table, 7, 2)
In this case it would either return a table with 2 and 5, or 1 and 6 depending on what it finds first. I am looking for where to even start on this, I have 0 clue how to make it. I also realize it’s exponential, and I will have to do some heavy optimization as the tables will have anywhere from 1 to 200 inputs.
local function GetTarget(Table, Target, Amount)
local Clone = table.clone(Table)
local NewTable = {}
for i = 1, Amount do
for j, v in pairs(Clone) do
if v == Target then
NewTable[i] = v
table.remove(Clone, j)
break
end
end
if not NewTable[i] then break end
end
return NewTable
end
in case i misunderstood the question here is another function
local function GetTarget(Table, Target, Amount)
local NewTable = {}
table.sort(Table)
for i, v in pairs(Table) do
if v >= (Target - Amount) then
for j = i, #Table do
table.insert(NewTable, Table[j])
if Table[j] >= (Target + Amount) then
break
end
end
break
end
end
return NewTable
end
I am not 100% sure what either of these do, but I am pretty sure neither of them are what I am looking for. I need something that takes a table, a desired value, and a desired amount, and returns a second table that has a amount of inputs that add up to (or as close as possible) the desired amount. Im pretty sure the first function you provided returns numbers that equal the value I want. I am not looking for that, I am looking for a way to find numbers that add up to the desired value. Im pretty sure the second function does something where it takes the amount away from the desired value? Im not sure.
I am looking for a function which takes a table as an input. It then returns a table that contains a number of entries that correlates to the Amount parameter. The entries add up to the Target parameter. If they cannot match the Target with values out of the table while still following the Amount parameter, the function tries to get as close as possible.
I am sorry if this is confusing, I can describe anything else you need. I also do not need to be provided with a function, I just need to figure out how one would even go about doing this.