将采用数字或单词并找到所有可能组合的算法 [英] algorithm that will take numbers or words and find all possible combinations

查看:25
本文介绍了将采用数字或单词并找到所有可能组合的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种算法,该算法将采用数字或单词并找到它们的所有可能变体,并让我定义要一起查找的值的数量.

I am looking for an algorithm that will take numbers or words and find all possible variations of them together and also let me define how many values to look for together.

例如,字符串或数组是:

Example lets say the string or array is:

cat  
dog  
fish  

那么值为 2 的结果可能是:

then the results for a value of 2 could be:

cat dog  
cat fish  
dog cat  
dog fish  
fish cat  
fish dog   

所以 3 个项目的结果是它在 2 个结果匹配时的 6 种可能变体
有 3 个匹配的结果将是:

SO the results from the set of 3 items are 6 possible variations of it at 2 results matching
with 3 results matching it would be:

cat dog fish  
cat fish dog  
dog cat fish  
dog fish cat  
fish cat dog  
fish dog cat  

...甚至可能有更多选择

...probably more options even

我在 Stackoverflow 上找到了一个指向此示例的链接,但它是在 javascript 中的,我想知道是否有人知道如何在 PHP 中执行此操作,也许已经构建了一些东西?

I have found a link on Stackoverflow to this example that does this but it is in javascript, I am wondering if anyone knows how to do this in PHP maybe there is something already built?

http://www.merriampark.com/comb.htm(死链接)

推荐答案

看一看 http://pear.php.net/package/Math_Combinatorics

<?php
require_once 'Math/Combinatorics.php';
$words = array('cat', 'dog', 'fish');
$combinatorics = new Math_Combinatorics;
foreach($combinatorics->permutations($words, 2) as $p) {
  echo join(' ', $p), "
"; 
}

印刷品

cat dog
dog cat
cat fish
fish cat
dog fish
fish dog

这篇关于将采用数字或单词并找到所有可能组合的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆