生成包含所有可能替换的列表

时间:2018-05-30 16:48:40

标签: algorithm replace lua

我真的不知道如何标题这个问题,但这正是我试图实现的:

一个函数,它接受一个字符串并返回一个包含所有可能组合的列表,用!替换该字符串中Any的出现次数。

示例:

gen_combinations('(test ! with !)')
=> {
    '(test ! with !)',
    '(test Any with !)',
    '(test Any with Any)',
    '(test ! with Any)'
}

1 个答案:

答案 0 :(得分:0)

function gen_combinations(str)
   local res = {}
   local count = 1
   str:gsub("!", 
      function() 
         count = count * 2 
      end
   )
   for mask = 0, count - 1 do
      table.insert(res, (str:gsub("!", 
         function() 
            mask = math.floor(mask) / 2
            if mask % 1 ~= 0 then 
               return "Any" 
            end 
         end
      )))
   end
   return res
end
相关问题