2017-05-06 128 views
0

我想从下面这种字符串中打印出所有可能的句子。什么是最好的方式来做到这一点?带多个分隔符和Concat的分割字符串

[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend 
  1. 我最好的朋友是
  2. 你最好的朋友是
  3. 他最好的朋友是
  4. 她最好的朋友是
  5. 我真正的朋友是
  6. 你真正的朋友是
  7. 他的真朋友
  8. 她真正的朋友是

  9. 谁是你最好的朋友

  10. 谁是她最好的朋友
  11. 谁是他最好的朋友
  12. 谁是你真正的朋友
  13. 谁是她真正的朋友
  14. 谁是他的真正朋友
  15. 哪里是你最好的朋友
  16. 她最好的朋友在哪里
  17. 那里是他最好的朋友
  18. 哪里是你真正的朋友
  19. 这里是她真正的朋友
  20. 那里是他真正的朋友
+0

写一堆循环。 – 2017-05-06 11:15:21

回答

1

有没有内置的功能,你需要什么。所以你需要制定一个解决方案。

首先你需要把这个任务分成更琐碎的部分。

一部分会接受阵列的阵列和在其上执行组合:

// Converts [['a'], ['b', 'c']] to ['ab', 'ac'] 
const combination = (parts) => { 
    let current = [[]] 
    parts.forEach(v => { 
    let result = [] 
    current.forEach(c => { 
     v.forEach(n => { 
     result.push(c.concat(n)) 
     }) 
    }) 
    current = result 
    }) 
    return current.map(v => v.join(' ')) 
} 

另一部分需要的输入转换成数组的数组和格式的输出:

const generate = (formats) => { 
 
    let result = [] 
 

 
    // Converts [['a'], ['b', 'c']] to ['ab', 'ac'] 
 
    const combination = (parts) => { 
 
    let current = [[]] 
 
    parts.forEach(v => { 
 
     let result = [] 
 
     current.forEach(c => { 
 
     v.forEach(n => { 
 
      result.push(c.concat(n)) 
 
     }) 
 
     }) 
 
     current = result 
 
    }) 
 
    return current.map(v => v.join(' ')) 
 
    } 
 
    formats.split('|').forEach((format) => { 
 
    let parts = format 
 
     .split(/[\]\[\)\(]/) // split "[a] (b) c" to ["a", "b", "c"] 
 
     .filter(String) // remove empy elements 
 
     .map(s => {return s.trim()}) 
 
     .filter(String) // there can be empty strings. remove those too 
 
    parts = parts.map(part => {return part.split('/')}) 
 
    result = result.concat(combination(parts)) 
 
    }) 
 
    return result 
 
} 
 

 
let input = "[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend" 
 
generate(input).forEach((v, i) => {console.log((i+1) + '. ' + v)})

这几乎是你需要的。虽然有一些角落案件应该被覆盖,并且.split(/[\]\[\)\(]/)行有点问题。但我相信你可以修复它。

+0

圆括号内的字符串是可选的。我也想打印出没有他们的可能的句子。我怎样才能做到这一点? – ovuncuzun

+0

@nanokozmos你可以将'(a/b)'转换为'[a/b /]'。 – teivaz

+0

如果某些可选字符串不需要额外空间会怎么样?例如“我喜欢/爱我的车”@teivaz – ovuncuzun