Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate word combinations

Tags:

php

word

For example this is my text :

$str = 'buy new microsoft windows';

I explode text and list with array :

Array
(
    [0] => buy
    [1] => new
    [2] => microsoft
    [3] => windows
)

I want to generate words in array to something like this:

buy new
buy new windows
buy microsoft 
buy microsoft windows
buy windows
new microsoft
new microsoft windows
new windows
microsoft windows

I tried with foreach and rand but I couldn't generate like showed. Is there any chance to generate just like my request?

like image 267
Morteza Avatar asked Jun 14 '11 11:06

Morteza


2 Answers

Found from php.net shuffle doc

function powerSet($in,$minLength = 1) { 
   $count = count($in); 
   $members = pow(2,$count); 
   $return = array(); 
   for ($i = 0; $i < $members; $i++) { 
      $b = sprintf("%0".$count."b",$i); 
      $out = array(); 
      for ($j = 0; $j < $count; $j++) { 
         if ($b{$j} == '1') $out[] = $in[$j]; 
      }
      $out_val = implode(" ", $out); 
      if (count($out) >= $minLength) { 
         $return[] = $out_val; 
      } 
   } 
   return $return; 
}

print_r(powerSet($str_arr));

and the results will be,

Array
(
    [0] => windows
    [1] => microsoft
    [2] => microsoft windows
    [3] => new
    [4] => new windows
    [5] => new microsoft
    [6] => new microsoft windows
    [7] => buy
    [8] => buy windows
    [9] => buy microsoft
    [10] => buy microsoft windows
    [11] => buy new
    [12] => buy new windows
    [13] => buy new microsoft
    [14] => buy new microsoft windows
)
like image 60
Paulraj Avatar answered Sep 23 '22 04:09

Paulraj


You can have a look at this PEAR PACKAGE Example usage:

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

The output will be:

buy new
new buy
buy microsoft
microsoft buy
new microsoft
microsoft new
like image 21
Sujit Agarwal Avatar answered Sep 21 '22 04:09

Sujit Agarwal