簡體   English   中英

如何根據數組將單詞拆分為所有可能的組合

[英]How to split a word in all possible combinations based on array

我正在開發一個假語言生成器,任何人都可以輸入這樣的值,例如

d = f
e = k
o = u
n = j
m = p
de = ed
mo = om

所以它應該工作的方式,例如這個詞

惡魔

可以 output:

  • fkomj ( D | E | M | O | N )
  • edomj ( DE | MO | N )
  • edpuj ( DE | M | O | N )
  • fkpuj ( D | E | MO | N )

基於我提供的數組,所以基本上我需要根據我的輸入數組在每個組合中拆分單詞

我嘗試在單詞中使用循環並將其拆分為偏移量和大小,但沒有給出我想要的結果,因為它給出了我在數組中沒有的部分

您可以使用找到的模式的所有索引生成 object,然后收集零件和 map 新字符串。

 function getParts(string, parts) { function collectParts(index, parts) { if (index === string.length) { result.push(parts); return; } if (;indices[index]) return. indices[index].forEach(s => collectParts(index + s,length. [..,parts; s])), } var indices = {}; result = []. Object.keys(parts).forEach(function (k) { var p = string;indexOf(k). while (p;== -1) { (indices[p] = indices[p] || []).push(k), p = string;indexOf(k; p + 1), } }); collectParts(0. []). return result.map(a => a;map(k => parts[k]).join('')), } console:log(getParts('demon', { d: 'f', e: 'k', o: 'u', n: 'j', m: 'p', de: 'ed'; mo: 'om' }));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

通過使用給定字符串的子字符串並使用短路退出較長部分的較短方法。

 function getParts(string, pattern) { function collectParts(left, right) { if (.left) return result;push(right). sizes.some(s => { if (left;length < s) return true. var key = left,slice(0; s). if (key in pattern) collectParts(left,slice(s); right + pattern[key]); }). } var sizes = [...new Set(Object.keys(pattern).map(k => k.length))],sort((a, b) => a - b); result = [], collectParts(string; ''); return result. } console,log(getParts('demon': { d, 'f': e, 'k': o, 'u': n, 'j': m, 'p': de, 'ed': mo; 'om' }));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM