【问题标题】:PHP combinations using all words each time [duplicate]每次使用所有单词的PHP组合[重复]
【发布时间】:2013-12-06 19:31:45
【问题描述】:

这是我在这个网站上的第一个问题,所以我希望我能足够具体。

我需要将文本字符串转换为多个数组,其中包含文本字符串中“单词”和“单词短语”的所有不同组合。

所以字符串会是这样的: “2013 年法国足球比赛”

从这里我想要以下数组:

array(
0 => array(
    'Football',
    'match',
    'France',
    '2013'
),
1 => array(
    'Football',
    'match',
    'France 2013'
),
2 => array(
    'Football',
    'match France',
    '2013'
),
3 => array(
    'Football',
    'match France 2013'
),
4 => array(
    'Football match',
    'France',
    '2013'
),
5 => array(
    'Football match',
    'France 2013',
),
6 => array(
    'Football match France',
    '2013'
),
7 => array(
    'Football match France 2013',
),

)

因此,每个结果字符串字符串可以由 1 到 n 个连续单词组成,并且每个子数组总共应该包含每个单词一次。

【问题讨论】:

  • 那么,你尝试了什么?
  • 这是你的作业,还是你真的需要它?

标签: php arrays string combinations


【解决方案1】:

这是一些有效的代码。

<?php 

$str = 'Football match France 2013'; // Initialize sentence
$words = explode(" ",$str); // Break sentence into words
$p = array(array(array_shift($words))); // Load first word into permutation that has nothing to connect to

foreach($words as $word) { // for each remaining word
    $a = $p; // copy existing permutation for not-connected set
    $b = $p;  // copy existing permutation for connected set
    $s = count($p); // cache number of items in permutation
    $p = array(); // reset permutation (attempt to force garbage collection before adding words)
    for($i=0;$i<$s;$i++) { // loop through each item
       $a[$i][] = $word; // add word (not-connected)
       $b[$i][count($b[$i])-1] .= " ".$word; // add word (connected)
    }
    $p = array_merge($a,$b); // create permutation result by joining connected and not-connected sets
}

// Dump the array
print_r($p);

?>

【讨论】:

  • 谢谢!我仍然对这里的快速响应感到惊讶。
  • 如果我明白你是如何怀孕的,我会很高兴的。
  • nl-x 这是一个排列问题,其中每个单词可以连接到前一个单词,也可以不连接到前一个单词。奇点案例(第一个单词)需要预先加载到缓冲区中,因为它没有任何要连接的东西。然后随着每个单词的添加,它会使数组的大小加倍,因为只有两种可能的状态(已连接,未连接)。连接新词的所有现有成员,以及未连接新词的所有现有成员。
  • nl-x 我添加了一些 cmets 让算法更容易理解。
  • @RalphRitoch 你想杀死 nl-x 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 2019-08-20
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
相关资源
最近更新 更多