PHP數組組合
類組合實現迭代儀 { 受保護的$ c = null; //數字組合 受保護的$ s = null; //源數組 保護$ n = 0; //數組中的元素數量 保護$ k = 0; //每種組合中的元素數量 受保護的$ pos = 0; //迭代器的當前位置 函數__construct($ s,$ k){ //初始化類屬性 如果(is_array($ s)){ $ this-> s = array_values($ s); $ this-> n = count($ this-> s); } 別的 { $ this-> s =(string)$ s; $ this-> n = strlen($ this-> s); } $ this-> k = $ k; $ this-> rewind(); } //返回當前密鑰 函數鍵(){ 返回$ this-> pos; } //返回當前值 功能電流(){ $ r = array(); 對於($ i = 0; $ i k; $ i) $ r [] = $ this-> s [$ this-> c [$ i]]; 返回is_array($ this-> s)? $ r:爆破('',$ r); } //移至下一個組合 函數next(){ 如果($ this-> _ next()) $ this-> pos; 別的 $ this-> pos = -1; } //倒帶到第一個組合 功能rewind(){ $ this-> c = range(0,$ this-> k); $ this-> pos = 0; } //檢查迭代器是否有效(在有效位置) 功能有效(){ 返回$ this-> pos> = 0; } //移至下一個組合(內部功能) 受保護函數_next(){ $ i = $ this-> k -1; while($ i> = 0&& $ this-> c [$ i] == $ this-> n-$ this-> k $ i) $ i--; 如果($ i c [$ i]; while($ i k -1) $ this-> c [$ i] = $ this-> c [$ i-1] 1; 返回true; } } //為給定數組創建一個組合對象和每個組合的元素數量 $組合=新組合(“ 1234567”,5); //迭代所有可能的組合併將其打印出來 foreach($組合為$ substring) echo $substring, ' ';This code produces the following output:
12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3