【发布时间】:2014-07-31 21:02:53
【问题描述】:
此问题与上述建议的问题不同。标题可能听起来相似,但其答案绝不会导致下面的问题。
我很难递归地遍历一个未知长度的数组来创建唯一的字符串组合。你能帮忙吗?
我们的目标是获取像foo bar 这样的字符串,并从该字符串创建唯一的组合:
foo
bar
bar_foo (alphabetized to make unique combinations, not permutations)
另一个例子:
car bar add 应该返回:
add
add_bar
add_car
add_bar_car
bar
bar_car
car
这是我的进步:
function string_builder($length) {
$arrWords = array('add','bar','car','dew','eat','fat','gym','hey','ink','jet','key','log','mad','nap','odd','pal','qat','ram','saw','tan','urn','vet','wed','xis','yap','zoo');
$arr = array();
for ($i=0; $i < $length; $i++) {
$arr[] = $arrWords[$i];
}
return implode(' ', $arr);
}
function get_combinations($string) {
$combinations = array(); // put all combinations here
$arr = explode(' ',$string);
$arr = array_unique($arr); // only unique words are important
sort($arr); // alphabetize to make unique combinations easier (not permutations)
$arr = array_values($arr); // reset keys
for ($i=0; $i < count($arr); $i++) {
// this is where I'm stuck
// how do I loop recursively through all possible combinations of an array?
}
return $combinations;
}
// Test it!
for ($i=1; $i < 26; $i++) {
$string = string_builder($i);
$combinations = get_combinations($string);
echo $i . " words\t" . count($combinations) . " combinations\t" . $string . "\n";
// print_r($combinations);
}
另一个尝试:
function getCombinations2($str, $min_length = 2) {
$words = explode(' ', $str);
$combinations = array();
$len = count($words);
for ($a = $min_length; $a <= $min_length; $a++) {
for ($pos = 0; $pos < $len; $pos ++) {
if(($pos + $a -1) < $len) {
$tmp = array_slice($words, $pos, $a);
sort($tmp);
$tmp = implode('_',$tmp);
$combinations[] = $tmp;
}
}
}
$combinations = array_unique($combinations);
return $combinations;
}
当您打印出组合并寻找应该存在的几个组合(例如,“fat_zoo”、“car_tan”)时,您就可以知道您成功了。我的两次尝试都会显示其中的几个,但不会显示全部。
【问题讨论】:
-
你到底想要什么?你想要所有音节的所有可能组合吗?你希望每个单词有多少个音节?
-
@MCEmperor,只是文字。
explode(' ',$str)很好。 -
我认为排列关心顺序?我不想要
bar_foo、bar_bar、foo_bar和foo_foo。我只想要其中一个(bar_foo,因为它更容易按字母顺序排列)。 -
组合不考虑顺序,因此 ABC 和 CBA 是相同的。排列关心顺序,因此将两者视为不同的。当订单很重要时,不同的订单是不同的子集,而不是相反
-
谢谢安东尼。我想同样对待
ABC和CBA。因此,按字母顺序对结果进行排序以确保CBA在包含ABC时永远不会出现。
标签: php arrays recursion combinations