且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中创建所有可能的组合

更新时间:2023-02-10 07:56:20

其中涉及一些步骤:


  1. 将同义词列表缩小到仅在字符串中找到的那些

  2. 从以下位置创建模板从而构建最终句子

  3. 获取所有同义词组合并将其应用于模板

  1. narrow down the list of synonyms to only those found in the string
  2. create a template from which to build the final sentences
  3. get all synonym combinations and apply them to the template

以下将做到这一点:

$dict = [
    '1' => ['a', 'b', 'c'],
    '2' => ['d', 'e'],
];

$str = '2, 1';

class SentenceTemplate implements IteratorAggregate
{
    private $template;
    private $thesaurus;

    public function __construct($str, $dict)
    {
        $this->thesaurus = [];

        $this->template = preg_replace_callback('/\w+/', function($matches) use ($dict) {
            $word = $matches[0];
            if (isset($dict[$word])) {
                $this->thesaurus[] = $dict[$word];
                return '%s';
            } else {
                return $word;
            }
        }, $str);
    }

    public function getIterator()
    {
        return new ArrayIterator(array_map(function($args) {
            return vsprintf($this->template, $args);
        }, $this->combinations($this->thesaurus)));
    }

    private function combinations($arrays, $i = 0) {
        if (!isset($arrays[$i])) {
            return array();
        }
        if ($i == count($arrays) - 1) {
            return $arrays[$i];
        }

        // get combinations from subsequent arrays
        $tmp = $this->combinations($arrays, $i + 1);

        $result = array();

        // concat each array from tmp with each element from $arrays[$i]
        foreach ($arrays[$i] as $v) {
            foreach ($tmp as $t) {
                $result[] = is_array($t) ? array_merge(array($v), $t) : array($v, $t);
            }
        }

        return $result;
    }
}

$sentences = new SentenceTemplate($str, $dict);
foreach ($sentences as $sentence) {
    echo "$sentence\n";
}

演示