lua使用协同程序实现迭代器-笔记

function printResult( a )
    local str = ""
    for i=1,#a do
        str = str .. a[i] .. " "
    end
    print("--" .. str .. "\n")
end

function permgen(a, n)
    n = n or #a
    if n <= 1 then
        coroutine.yield(a) --完成一次排列 返回排列数组;挂起 保存迭代状态
    else
        for i=1,n do --每循环一次 生成一个a[i]所有位置变化的数组
            a[n], a[i] = a[i], a[n] --交换
            permgen(a, n - 1) -- 递归实现a[i]位置交换 每次循环交换至n-1
            a[n], a[i] = a[i], a[n] --还原 方便下个元素交换
        end
    end
end

function permutations(a)
    local co = coroutine.create(function () --创建协程
        permgen(a)
    end)
    return function ()
        local code, res = coroutine.resume(co) --每次调用迭代函数,即唤醒协同程序 产生一个值
        return res
    end
end

--迭代打印
for p in permutations{"a", "b", "c"} do
    printResult(p)
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值