Lua 中如何从一个非常长的字符串中快速获取随机匹配模式?

我有一个超过 200 万个字符的字符串,我觉得我当前的从模式中找到随机匹配的方法不够快。

local function getRandomMatch(string, pattern)
    local occurenceCount = select(2, string.gsub(string, pattern, ""))
    local index, randomIndex = 0, math.random(1, occurenceCount)
    for match in string:gmatch(pattern) do
        index = index + 1
        if index == randomIndex then
            return match
        end
    end
end

有没有一种方法可以让它更快?

点赞
用户6834680
用户6834680

本地变量findrandommatch分别引用字符串函数findrandommatch

局部函数getRandomMatch获取一个字符串并一个模式,返回一个随机匹配的字符串。

循环结构执行20次局部函数getRandomMatch,每次传入字符串"1234"和模式"%d%d",并输出结果。

代码如下:

local find, random, match = string.find, math.random, string.match

local function getRandomMatch(string, pattern)
   local pos, random_pos = 0, 0
   for cnt = 1, math.huge do
      pos = find(string, pattern, pos + 1)
      if not pos then
         return match(string, pattern, random_pos)
      elseif random(cnt) == 1 then
         random_pos = pos
      end
   end
end

for j = 1, 20 do
   print(getRandomMatch("1234", "%d%d"))
end

更新:

快速、简单的解决方案:

(“Dirty”表示“匹配是随机的,但是选择的概率不同”)

local random, match = math.random, string.match

local function getRandomMatchFastAndDirty(string, pattern)
   return match(string, pattern, random(#string)) or match(string, pattern)
end
2018-08-07 14:34:27