【问题标题】:Lua find random key match in TableLua在表中找到随机键匹配
【发布时间】:2019-11-03 16:37:38
【问题描述】:

我有一个带有和弦名称和开始时间的和弦表,在不同的开始时间有许多相同的名称。我需要随机选择一个匹配的chord_name

chord_name = "Cm7b5"
time = chords[chord_name].Start

【问题讨论】:

  • 由于表在给定的键上只能包含一个值,并且您使用 chord_name 作为键,因此同名的和弦不能超过一个。您确定您的表格是 chords[chord_name] 而不是例如 chords[some_index].Name
  • 是的,很抱歉,这会得到我需要的东西,一个与名称匹配的随机索引> chords[some_index].Name

标签: lua


【解决方案1】:

因此,如果您需要从chords 中选择一个随机的chord,以便chords[index].Name == chord_name 和您的索引一个接一个,例如:1、2、3、4、5(而不是例如:52、96 , 121) 你可以这样做:

chord_name = "Cm7b5"

index = math.random(#chords)
while chords[index].Name ~= chord_name do
    index = math.random(#chords)
end

time = chords[index].Start

(请注意,我没有选择和弦,而是 .Start 时间,正如您的示例所示。)

但是,如果您有大量数据并且只有少数数据有.Name == chord_name,则这很有可能(几乎)无限循环。

因此,确保对math.random() 的单次调用将给我们一个明确的答案(索引)是一个好主意。

chord_name = "Cm7b5"

--we create an empty table
indexes = {}

--and store all indexes that fulfil the condition chords[index].Name == chord_name
for index, chord in pairs(chords) do
    if chord.Name == chord_name then
        table.insert(indexes, index)
    end
end

--now we can randomly select from this table
index = indexes[math.random(#indexes)]

--which will always yield an index pointing to a chord with .Name == chord_name
time = chords[index].Start

请注意,使用pairs(chords) 还允许从有孔的表格中选择和弦(即{[1] = "a", [5] = "b", [16] = "c"})。

另一方面,如果您有大量(可能是数百万或 100k)数据,则后一种解决方案可能会出现问题。迭代整个表并选择匹配的名称并基于它创建一个新表将非常耗时和消耗内存。

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2019-07-30
    • 2017-06-04
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多