【问题标题】:Lua - how to sort a table by the value chainLua - 如何按价值链对表进行排序
【发布时间】:2015-09-12 16:40:43
【问题描述】:

我正在寻找一种按值链对 Lua 表进行排序的方法。说,桌子:

local vals = {
{ id = "checkpoint4" },
{ id = "checkpoint1", nextid = "checkpoint2" },
{ id = "checkpoint3", nextid = "checkpoint4" },
{ id = "checkpoint2", nextid = "checkpoint3" },
}

排序后应该变成这个:

local vals = {
{ id = "checkpoint1", nextid = "checkpoint2" },
{ id = "checkpoint2", nextid = "checkpoint3" },
{ id = "checkpoint3", nextid = "checkpoint4" },
{ id = "checkpoint4" },
}

本质上并不是完全相同的名称,它们可能会有所不同。我想在“检查点”之后对数字进行比较,但事实证明我必须使用这样的动态事物(已经按照我想要的方式排序):

local vals = {
{ id = "checkpoint1", nextid = "cp" },
{ id = "cp", nextid = "chp" },
{ id = "chp", nextid = "mynextcheckpoint" },
{ id = "mynextcheckpoint"},
}

谢谢。

【问题讨论】:

    标签: sorting lua lua-table chain


    【解决方案1】:

    您所描述的内容称为topological sorting。但是,由于这是一种受限情况,我们不必实现完整的拓扑排序算法:

    function sort_list(tbl)
      local preceding = {}
      local ending
      local sorted = {}
      for i, e in ipairs(tbl) do
        if e.nextid == nil then
          ending = e
        else
          preceding[e.nextid] = i
        end
      end
      if ending == nil then
        return nil, "no ending"
      end
      local j = #tbl
      while ending ~= nil do
        sorted[j] = ending
        ending = tbl[preceding[ending.id]]
        j = j - 1
      end
      if sorted[1] == nil then
        return nil, "incomplete list"
      end
      return sorted
    end
    

    用法:

    local sorted = sort_list(vals)
    

    【讨论】:

      【解决方案2】:
      local id2val, tailsizes = {}, {}
      for _, val in ipairs(vals) do id2val[val.id] = val end
      
      local function tailsize(val)  -- memoized calculation of tails sizes
         if not tailsizes[val] then
            tailsizes[val] = 0                         -- cycle-proof
            if val.nextid and id2val[val.nextid] then  -- dangling nextid proof
               tailsizes[val] = tailsize(id2val[val.nextid]) + 1
            end
         end
         return tailsizes[val]
      end
      
      -- sorting according to tails sizes
      table.sort(vals, function(a,b) return tailsize(a) > tailsize(b) end)
      

      【讨论】:

        猜你喜欢
        • 2020-02-08
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-20
        • 2013-07-29
        相关资源
        最近更新 更多