douqiao2008 2013-09-17 21:08
浏览 19

PHP中的缩写排列

I'm trying to write a small routine responsible for permuting all possible abbreviations for a string. This string is a full name, separated by spaces. Like this:

James Mitchell Rhodes

I want to output:

J. Mitchell Rhodes
James M. Rhodes
J. M. Rhodes

And so on... however, i also have to consider "stopwords":

James the Third Rhodes

I want to output:

J. the Third R.
James The Third R.

Is there a known algorithm for this? I've been trying to fix this problems for quite some time now.

UPDATE: Having each word in array is dead easy. Just explode(' ', $string) and then array_map, to exclude the stop words considering in_array($word, $stopWordsMap). This is NOT the problem, and NOT the focus of the question. The problem is how to discover the combination of possible Original words (O) and Abbreviated words (A):

O A A
O A O
O A A
A A A
O O O
  • 写回答

2条回答 默认 最新

  • dtn913117 2013-09-17 21:40
    关注

    I am not gonna write the full code, since you said permuting is not the issue. This is about figuring out which words to permute for all scenarios.

    I had to think of the binary system, stay with me on this on xD if you want to have all the possible inputs to a function with n inputs, you need 2^n input scenarios.

    so for you 2 inputs you wolud have

    0 0
    0 1
    1 0
    1 1
    

    alright? we can get this as an array in php with

    $map = array();
    $inputs = 2;
    for($i=0;$i<=2^$inputs;$i++){
        $bin = decbin($i);  // returns string
        $array = preg_split('//', $bin, -1, PREG_SPLIT_NO_EMPTY); // but i want a array
        $map[] = $array;
    }
    

    Now if your string that you want to permute has three words, see them as three inputs, and then all the $map rows tell you which word to permute every time to get all possibly strings, if the first item in that row is 0, dont permute the first word, if it is 1 permute the first word and so on..

    Here are all the rows and the resulting string for your example

    0 0 0  James Mitchell Rhodes
    0 0 1  James Mitchell R,
    0 1 0  James M. Rhodes
    0 1 1  James M. R.
    1 0 0  J. Mitchell Rhodes
    1 0 1  J. Mitchell R.
    1 1 0  J. M. Rhodes
    1 1 1  J. M. R
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改