Lua中如何获取嵌套表内字符的所有拼接组合并按行输出字符串
Lua嵌套表字符全排列拼接实现
你需要的效果本质是计算嵌套表中所有子表元素的笛卡尔积后按子表顺序拼接,以下实现兼容任意子表数量、任意子表元素个数:
直接输出版
-- 递归生成所有拼接结果并打印 function printAllCombinations(nestedTbl, depth, prefix) depth = depth or 1 prefix = prefix or "" -- 遍历完所有子表时输出当前拼接结果 if depth > #nestedTbl then print(prefix) return end -- 遍历当前层所有字符,递归拼接下一层 for _, char in ipairs(nestedTbl[depth]) do printAllCombinations(nestedTbl, depth + 1, prefix .. char) end end -- 测试调用 local c = { {'1','2','3'}, {'a','b','c'}, {'A','B','C'} } printAllCombinations(c)
结果存表版
如果需要把结果存储到新表中后续使用,可以用以下实现:
function getAllCombinations(nestedTbl, depth, prefix, result) depth = depth or 1 prefix = prefix or "" result = result or {} if depth > #nestedTbl then table.insert(result, prefix) return result end for _, char in ipairs(nestedTbl[depth]) do getAllCombinations(nestedTbl, depth + 1, prefix .. char, result) end return result end -- 测试调用 local c = { {'1','2','3'}, {'a','b','c'}, {'A','B','C'} } local results = getAllCombinations(c) -- 遍历验证结果 for _, str in ipairs(results) do print(str) end
运行上述代码即可得到你示例中列出的所有拼接结果。
内容的提问来源于stack exchange,提问作者HexaG0n YT
相关产品推荐
相关产品推荐

