on mGetFactorial ( me , num) factorial = 1 repeat with x = num down to 1 factorial = factorial * x end repeat return factorial end
接下来,就可以利用这个阶乘计算程序得到组合的总数:
-- 计算阶乘 listFactorial = me .mGetFactorial(pListCount) subsetFactorial = me .mGetFactorial(pSubsetCount) listMinusSubsetFactorial = me .mGetFactorial(pListCount - pSubsetCount) -- 计算组合总数 pTotal = listFactorial / (subsetFactorial * (listMinusSubsetFactorial)) pNumLeft = pTotal
现在,借助一个索引数值,通过循环语句即可生成一个索引列表:
on mGetCombination ( me ) -- 检测是否为第一次循环 if pNumLeft = pTotal then -- 是第一次循环,使用当前子列表 pNumLeft = pNumLeft - 1 else -- 不是第一次循环,获取新的子列表 x = pSubsetCount -- 在当前子列表中循环并增值 repeat while pCurrentSubset[ x ] = pListCount - pSubsetCount + x x = x - 1 end repeat pCurrentSubset[ x ] = pCurrentSubset[ x ] + 1 repeat with y = ( x + 1 ) to pSubsetCount pCurrentSubset[ y ] = pCurrentSubset[ x ] + y - x end repeat -- 获取新的子列表 pNumLeft = pNumLeft - 1 end if end