2017-05-06 237 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