Поиск популярного значения.

Tema05

Известный
Автор темы
1,442
402
Версия MoonLoader
.026-beta
Допустим есть массив {"text", "go", "text", "", "go" "text"}
Нужно найти в нём самое частое значение, а именно "text". Как это можно эффективно сделать?
 
Решение
O(n)
Lua:
function mode(table)
  if #table == 0 then return nil end
  local modeMap = {}
  local maxEl = table[1]
  local maxCount = 1
  for i, v in ipairs(table) do
    modeMap[v] = (modeMap[v] or 0) + 1
    if modeMap[v] > maxCount then
      maxEl = v
      maxCount = modeMap[v]
    end
  end
  return maxEl
end

print(mode({"text", "go", "text", "", "go", "text"})) -- text
print(mode({"text", "go", "go", "go", "text", "", "go", "text"})) -- go

Akionka

akionka.lua
Проверенный
742
500
O(n)
Lua:
function mode(table)
  if #table == 0 then return nil end
  local modeMap = {}
  local maxEl = table[1]
  local maxCount = 1
  for i, v in ipairs(table) do
    modeMap[v] = (modeMap[v] or 0) + 1
    if modeMap[v] > maxCount then
      maxEl = v
      maxCount = modeMap[v]
    end
  end
  return maxEl
end

print(mode({"text", "go", "text", "", "go", "text"})) -- text
print(mode({"text", "go", "go", "go", "text", "", "go", "text"})) -- go