PHP中阶乘的置换

编程入门 行业动态 更新时间:2024-10-27 16:30:09
本文介绍了PHP中阶乘的置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

不知道该怎么解释.但是也许下面的例子可以使您理解我的问题所在.

示例:

我有一个包含3个元素的数组.

$elements = array( 'A', 'B', 'C' );

排列为3的3.因此结果为:

A-B-C ; A-C-B ; B-A-C ; B-C-A ; C-A-B; C-B-A

我不希望任何三分之二的排列或三分之一的排列,例如示例中所示的三分之三.因此,如果我在一个数组中有4个元素,则排列为4中的4.依此类推...

(我认为排列的数目是3!= 1 * 2 * 3 = 6个排列,4!= 1 * 2 * 3 * 4 = 24个排列...这就是为什么我称之为阶乘排列的原因.)

如果还有其他与我的问题类似的问答,请让我知道

解决方案

使用递归函数:

function permutations($elements) { if(count($elements)<2) return $elements; $newperms= array(); foreach($elements as $key=>$element) { $newelements= $elements; unset($newelements[$key]); $perms= permutations($newelements); foreach($perms as $perm) { $newperms[]= $element."-".$perm; } } return $newperms; }

没有测试过,所以仍然可以为您工作;-)

Don't know how to explain. But maybe example below will be make you understandable what my problem is.

Example :

I have an array with 3 elements.

$elements = array( 'A', 'B', 'C' );

The permutation will be 3 in 3. so the result are :

A-B-C ; A-C-B ; B-A-C ; B-C-A ; C-A-B; C-B-A

I don't want any permutation 2 in 3 or 1 in 3, just 3 in 3 as you can see in example. So if I have 4 elements in an array, the permutation is 4 in 4. and so on...

(I think the number of permutations is 3! = 1*2*3 = 6 permutations, 4! = 1*2*3*4 = 24 permutations... that why I call Permutations of Factorial.)

If there are other question and answer similar to my problem, please let me know

解决方案

Use a recursive function:

function permutations($elements) { if(count($elements)<2) return $elements; $newperms= array(); foreach($elements as $key=>$element) { $newelements= $elements; unset($newelements[$key]); $perms= permutations($newelements); foreach($perms as $perm) { $newperms[]= $element."-".$perm; } } return $newperms; }

Didn't test it, so there is still work for you ;-)

更多推荐

PHP中阶乘的置换

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

发布评论

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

>www.elefans.com

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