Example of Simple Word Group Algorithm Implemented by PHP

  • 2021-09-20 19:39:31
  • OfStack

In this paper, an example is given to describe the simple word group algorithm implemented by PHP. Share it for your reference, as follows:


<?php
// Word formation algorithm 
function diyWords($arr,$m){
  $result = array();
  if ($m ==1){// Only left 1 Return directly when you have a word 
    return $arr;
  }
  if ($m == count($arr)){
    $result[] = implode('' , $arr);
    return $result;
  }
  $temp_firstelement = $arr[0];
  unset($arr[0]);
  $arr = array_values($arr);
  $temp_list1 = diyWords($arr, ($m-1));
  foreach ($temp_list1 as $s){
    $s = $temp_firstelement.$s;
    $result[] = $s;
  }
  $temp_list2 = diyWords($arr, $m);
  foreach ($temp_list2 as $s){
    $result[] = $s;
  }
  return $result;
}
// Word formation algorithm 
$arr=array(' Trousers ',' Cowboy ',' Low waist ',' Fattening ');
$count=count($arr);
for($i=1;$i<=$count;$i++){
  $temp[$i]=diyWords($arr,$i);
}
echo '<pre/>';print_r($temp);

Run results:

Array
(
[1] = > Array
(
[0] = > Trousers
[1] = > Cowboy
[2] = > Low waist
[3] = > Fattening
)
[2] = > Array
(
[0] = > Trousers denim
[1] = > Low-waisted trousers
[2] = > Fattening trousers
[3] = > Low-waisted cowboy
[4] = > Denim fattening
[5] = > Low waist fattening
)
[3] = > Array
(
[0] = > Trousers denim low waist
[1] = > Trousers denim fattening
[2] = > Low waist and fat trousers
[3] = > Low waist fattening of denim
)
[4] = > Array
(
[0] = > Pants, denim, low waist and fat
)
)

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this paper is helpful to everyone's PHP programming.


Related articles: