How do I check for highest quantity of duplicates in a table?

so basically i have a table here (the table has random names and not specific names) image
and i want the it to print the most relevant item (which is GroovyDominoes52)
any tips on how to do this?
(im making a script to kick player who appears the most in the table)

1 Like

There’s a few ways you can solve it, but in the end you’d achieve the same result.

You could iterate through this table and save a count of total occurrences in the form of an array or key/value pair. From there you could either use table.sort() or a quick comparison check to get the highest count.

3 Likes

There are many ways you could do this. A standard way in O(N^2):

local values = {4,4,5,1,2,3,5,5,5}

function getMaxFreqDuplicate(array) 
    local bin = {}
    local highestFrequency = -math.huge
    local finalElement;
 
    for i, v in pairs(array) do 
        local tempFrequency = 0
        
        if not table.find(bin, v) then
            for j, k in pairs(array) do
                if v == k then 
                    tempFrequency += 1
                    if tempFrequency > highestFrequency then
                       finalElement = v
                       highestFrequency = tempFrequency  
                    end
                end
            end
        end
        bin[#bin + 1] = v
    end

    return finalElement
end

print(getMaxFreqDuplicate(values)) -- 5

We have a bin array which consists of the element we have already checked the frequency for. The highest frequency (initially negative infinity) and the final value to return. We loop through the array, and check the frequency for each element, if this frequency is greater than the highest frequency. We set finalElement to the value and at the end return it.

You could also use table.sort and then have a linear scan to check the frequency for consecutive duplicate values and get the value with the highest frequency accordingly.

3 Likes
local dict1 = {
	"a",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"a",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
	"GroovyDominoes52",
}

local dict2 = {}

for i, v in pairs(dict1) do
	if dict2[v] then
		dict2[v] += 1
	else
		dict2[v] = 1	
	end
end

for i, v in pairs(dict2) do
	print("The entry "..i.." occurs "..v.." times within the table.")
end
3 Likes

thanks alot! its exactly what i was trying to do.

1 Like