gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:32:25 24 4
gpt4 key购买 nike

我正在开发一个假语言生成器,任何人都可以输入这样的值,例如

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

它应该如何工作,例如这个词

demon

可以输出:

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

基于我提供的数组,所以基本上我需要根据我的输入数组在每个可能的组合中进行单词分割

我尝试使用单词中的循环并将其拆分为偏移量和大小,但没有给出我想要的结果,因为它提供了我在数组中没有的部分

最佳答案

您可以生成一个包含找到模式的所有索引的对象,然后收集各个部分并映射新字符串。

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; }

关于javascript - 如何根据数组将单词拆分为所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com