【问题标题】:Searchable tagged tables in lua?lua中可搜索的标记表?
【发布时间】:2014-03-12 09:05:50
【问题描述】:

所以我需要根据一些标签来搜索表格。

它需要根据标签的数量创建匹配列表。 因此,如果我们有一个匹配的 4 个标签将是一个列表,3 个标签是另一个列表,2 个是另一个。

您将如何使用 lua 表实现这一点?

我不想要太复杂的东西,如果有一个库或接口与一个设置不复杂的数据库,就可以了。

但如果不是,我可以以速度和内存为代价接受本机解决方案。

我所说的标签是这个

假设我们有桌子

T[1] ={cat,mouse bat, fly, car, aircraft,glider}

其中一些术语,如 bat、fly、airplane、glider 将具有可飞行标签。

另一个标签可以是汽车和飞机的机器。

另一个标签是动物:cat,mouse,bat,fly

因此,如果您同时使用 flyable + machine 这两个标签进行搜索,您会得到 airpalne 如果你搜索animal+flyable,你会得到bat and fly。

所以我需要一个结构来包含这个标签信息,让我可以轻松搜索。

【问题讨论】:

  • 什么是标签?我不明白你的意思。使用代码来解释你期望的输入和输出。

标签: search data-structures lua lua-table


【解决方案1】:

集合可能是您正在寻找的数据结构类型。请按照Programming in Lua 书中的说明查看 Set。

【讨论】:

  • Intersection 是我需要的东西,但我不确定它的比较功能是否正确。
【解决方案2】:
function findtable(table,value)
        for k,v in pairs(table) do
                if (v == value) or (k == value) then
                        return true
                end
        end
        return false
end

function tagged_flyable(value)
    local flyable_table = {'bat','fly','airplane','glider'}
    if(findtable(flyable_table,value) == true) then
        return true
    else 
        return false
    end
end

function tagged_animals(value)
    local animals_table = {'cat','mouse','bat','fly'}
    if(findtable(animals_table,value) == true) then
        return true
    else 
        return false
    end
end

function tagged_machines(value)
    local machines_table = {'car', 'airplane'}
    if(findtable(machines_table,value) == true) then
        return true
    else 
        return false
    end
end

-- main process
local T_1 = {'cat','mouse', 'bat', 'fly', 'car', 'airplane', 'glider'}
local search_results = {}
-- search for tag: flyable+machine
for i=1,table.getn(T_1) do
    if(tagged_machines(T_1[i]) and tagged_flyable(T_1[i])) then
        table.insert(search_results, T_1[i])
        print("found :", T_1[i])
    end
end


-- search for tag: flyable+animals
search_results = {}
for i=1,table.getn(T_1) do
    if(tagged_animals(T_1[i]) and tagged_flyable(T_1[i])) then
        table.insert(search_results, T_1[i])
        print("found :", T_1[i])
    end
end

【讨论】:

    【解决方案3】:

    最简单的方法是一个标签表,加上两个结果表。标签表:

    T = {cat={"animal", "legs"}, bat={"animal", "wings"}, ...}
    

    结果表只是对象带有特定标签的常规表:

    res1 = get(T, "wings")
    print(res1) -- prints cat bat plane 
    res2 = get(T, "machine")
    print(res2) -- prints car train plane
    

    然后是一个找到两个结果交集的函数:

    bothTags = getIntersection(res1,res2)
    

    getIntersection() 只需要遍历第一个表 res1 并测试 res2[itemFromFirstTable] 是否为 nil,如果不是,则您在两个表中都有一个项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 2013-05-22
      • 2015-04-26
      • 2015-07-02
      相关资源
      最近更新 更多