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