简体   繁体   English

如何根据数组将单词拆分为所有可能的组合

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

I'm working on a fake language generator that anyone can input the values like this for example我正在开发一个假语言生成器,任何人都可以输入这样的值,例如

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

So the way it should work, for example the word所以它应该工作的方式,例如这个词

demon恶魔

can output:可以 output:

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

based on the array i supplied, so basically for i need the word split in each combination possible based on my input array基于我提供的数组,所以基本上我需要根据我的输入数组在每个组合中拆分单词

I've tried working with an loop in the word and splitting it in offsets and sizes but didnt gave the result i wanted because it was giving parts that i didnt had in the array我尝试在单词中使用循环并将其拆分为偏移量和大小,但没有给出我想要的结果,因为它给出了我在数组中没有的部分

You could generate an object with all indices of the found pattern and then collect the parts and map new strings.您可以使用找到的模式的所有索引生成 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; }

A shorter approach by using substrings of the given string and using a short circuit to exit longer parts.通过使用给定字符串的子字符串并使用短路退出较长部分的较短方法。

 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