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