获取PHP数组的所有排列?

编程入门 行业动态 更新时间:2024-10-26 22:23:55
本文介绍了获取PHP数组的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出一个PHP字符串数组,例如:

Given a PHP array of strings, e.g.:

['peter', 'paul', 'mary']

如何生成此数组元素的所有可能排列?即:

How to generate all possible permutations of elements of this array? i.e.:

peter-paul-mary peter-mary-paul paul-peter-mary paul-mary-peter mary-peter-paul mary-paul-peter

推荐答案

function pc_permute($items, $perms = array()) { if (empty($items)) { echo join(' ', $perms) . "<br />"; } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); pc_permute($newitems, $newperms); } } } $arr = array('peter', 'paul', 'mary'); pc_permute($arr);

function pc_next_permutation($p, $size) { // slide down the array looking for where we're smaller than the next guy for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { } // if this doesn't occur, we've finished our permutations // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) if ($i == -1) { return false; } // slide down the array looking for a bigger number than what we found before for ($j = $size; $p[$j] <= $p[$i]; --$j) { } // swap them $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // now reverse the elements in between by swapping the ends for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; } $set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells') $size = count($set) - 1; $perm = range(0, $size); $j = 0; do { foreach ($perm as $i) { $perms[$j][] = $set[$i]; } } while ($perm = pc_next_permutation($perm, $size) and ++$j); foreach ($perms as $p) { print join(' ', $p) . "\n"; }

docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm

更多推荐

获取PHP数组的所有排列?

本文发布于:2023-11-30 10:11:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649613.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   排列   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!