Lua - 如何通过价值链对表进行排序

时间:2015-04-18 16:16:46

标签: sorting lua lua-table chain

我正在寻找一种按其价值链对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"},
}

感谢。

1 个答案:

答案 0 :(得分:3)

您所描述的内容称为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)