用lua实现一个效果,输入一个字符串,输出该字符串中所有的字符组合

#!/usr/bin/env lua 
function  th_table_dup(ori_tab)                      -- 复制table
     if  ( type (ori_tab) ~=  "table" then
         return  nil;
     end
     local  new_tab = {};
     for  i, v  in  pairs(ori_tab)  do
         local  vtyp =  type ( v );
         if  (vtyp ==  "table" then
             new_tab[i] = th_table_dup( v );
         elseif (vtyp ==  "thread" then
             -- TODO: dup or just point to?
             new_tab[i] =  v ;
         elseif (vtyp ==  "userdata" then
             -- TODO: dup or just point to?
             new_tab[i] =  v ;
         else
             new_tab[i] =  v ;
         end
     end
     return  new_tab;
end
 
function  permutation(s1,p)
     if  #s1 == 1 then                                -- 如果s1长度为1,意味着获得了一种新的排列
         p = p .. s1[1]                              -- 那么就打印它
         print(p)
     else                                             -- 否则,选定一种方案,继续递归
         local  i
         for  i = 1,  #s1 do                           -- 4.3 Control Structure; Numeric for
             local  p2, s2
             p2 = p .. s1[i]
             s2 = th_table_dup(s1)                   -- 把s1表的内容复制给s2表
             table.remove(s2,i)                      -- 20.1 Insert and Remove
             permutation(s2,p2)                      -- 用s2继续进行递归
         end
     end
end
 
-- 主程序
a = io. read ()                                       -- 读入字符串,可含汉字
                                                     -- 22.1 The Simple I /O  Model
len =  #(string.gsub(a, "[\128-\191]", ""))          -- 计算字符数(不是字节数)
 
i=1                                                 -- 迭代出每一个字符,并保存在table中
s = {}                                              -- 21.1 Basic String Functions
for  in  string.gmatch(a,  ".[\128-\191]*" do        -- 21.2 Pattern-Matching Functions
     s[i]=c                                          -- 21.7 Unicode
     i=i+1
end
 
print( "permutation output:" )
p= ""
permutation(s,p)                                    -- 递归打印出全排列
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值