local final_res = {} local function amb(wordsets, res) if #wordsets == 0 then table.move(res, 1, #res, #final_res + 1, final_res) return true end local s = "" local l = #res if l > 0 then s = res[l] end res:insert("") for wordsets[1] as word do res[l + 1] = word if l > 0 and s[-1] != res[l + 1][1] then continue end if amb(wordsets:slice(2), res:clone()) then return true end end return false end local wordsets = { { "the", "that", "a" }, { "frog", "elephant", "thing" }, { "walked", "treaded", "grows" }, { "slowly", "quickly" } } if amb(wordsets, {}) then print(final_res:concat(" ")) else print("No amb found") end