zoukankan      html  css  js  c++  java
  • 排列组合:01转换法之lua实现

    c++ 版连接 https://blog.csdn.net/canguanxihu/article/details/46363375

    因为项目用的是lua脚本,看了C++版后自己写了一个lua版本的,原理在c++连接里面博主已经介绍了,我也不重复描述了,直接把代码贴出来

     1 local NewLogic = class("NewLogic")
     2 
     3 local handCardCount = 13
     4 
     5 --随机生成扑克用于测试
     6 function NewLogic:randomMakeCards()
     7 
     8     math.randomseed(os.time())
     9 
    10     local cards = {}
    11 
    12     repeat
    13         local card = math.random(52)
    14         if not table.indexof(cards,card) then
    15             table.insert(cards,card)
    16         end
    17     until(#cards == handCardCount)
    18 
    19     return cards
    20 end
    21 
    22 
    23 -- o 1 转换排列组合法
    24 function NewLogic:combination(cards,cbntNumber)
    25     if cbntNumber > #cards then
    26         return nil
    27     end
    28 
    29     local assistArray = {}
    30     for i = 1,#cards do
    31         if i <= cbntNumber then
    32             assistArray[i] = 1
    33         else
    34             assistArray[i] = 0
    35         end
    36     end
    37 
    38     local cbntResult = {}
    39 
    40     local function getResult(astArray,srcArray,cbntResult)
    41         local oneOfCombination = {}
    42         for k,v in ipairs(astArray) do
    43             if v == 1 then
    44                 table.insert(oneOfCombination,srcArray[k])
    45             end
    46         end
    47 
    48         table.insert(cbntResult,oneOfCombination)
    49     end
    50 
    51     getResult(assistArray,cards,cbntResult)
    52 
    53     local idx = 1
    54     while true do
    55         if assistArray[idx + 1] == nil then
    56             break
    57         end
    58 
    59         if assistArray[idx] == 1 and assistArray[idx + 1] == 0 then
    60             assistArray[idx] = 0
    61             assistArray[idx + 1] = 1
    63 for i = 1 , idx -1 do 64 for j = i + 1, idx do 65 if assistArray[i] < assistArray[j] then 66 local mid = assistArray[i] 67 assistArray[i] = assistArray[j] 68 assistArray[j] = mid 69 end 70 end 71 end
             getResult(assistArray,cards,cbntResult)
    72 idx = 1 73 else 74 idx = idx + 1 75 end 76 end 77 78 return cbntResult 79 end 80 81 return NewLogic
  • 相关阅读:
    权限和分组
    验证与授权
    CSRF、XSS、clickjacking、SQL 的攻击与防御
    上下文处理器及中间件
    类和实例
    偏函数
    生成器
    迭代 复习
    函数调用 复习
    复习 条件判断,循环
  • 原文地址:https://www.cnblogs.com/abelmou/p/9291025.html
Copyright © 2011-2022 走看看