The name is pretty self-explanatory. Whenever I use table.find(table, duplicatevalue) on a table that I know has multiple of the same values, It says I just have 1. Thanks for reading if you need any code samples, just say so
table.find(t, element)
finds the index position of element
. It returns nil
if there is no element in the table. This does not give the number of duplicate values in the table.
Its uses are
- Quick verification that an element is in the table
- Get the index of the element, probably so you can pop it from the list or any other index-based operations rather than element based
Thanks! How would I go about efficiently finding the number of duplicates in a table from a provided string?
This problem occurs in O(n)
, you need to iterate over the table and check values individually. You can then do with it as you like, whether it be counting the number of duplicate values, finding the indexes of duplicate values, etc.
for instance
local tab = {1,4,1,7,1}
local function getDuplicates(t, duplicateValue)
local count = 0
for index, value in ipairs(t) do
if value == duplicateValue then
count += 1
end
end
return count
end
print(getDuplicates(tab, 1)) -- prints 3
local quantity = 0
local hasInGUI = 0
for _,h in pairs(frameNames) do
if h == v.Name then
hasInGUI = hasInGUI + 1
end
end
for _,h in pairs(foldNames) do
if h == v.Name then
quantity = quantity + 1
end
end
when i add one to the “foldNames” table that is a duplicate it kinda goes crazy
A function like @Scarious stated, that uses a for loop to iterate over an entire table with the (sad…) time complexity of O(n)
:
local function DupesInTable(Table,SearchTerm)
assert(typeof(Table) == "table", ("table required, %s was passed."):format(typeof(Table))))
if SearchTerm == nil then
return
end
local Dupes = 0
for _,Value in pairs(Table) do
if Value == SearchTerm then
Dupes += 1
end
end
return Dupes
end
Didn’t see that @Scarious had already posted code in response to his logic, still gonna leave this here for anyone else.