gpt4 book ai didi

javascript - 如何将一串句子分成两半,分成两个字符串的数组,每个字符串的长度尽可能相似?

转载 作者:行者123 更新时间:2023-11-29 10:02:13 25 4
gpt4 key购买 nike

我这里有一个有趣的问题。我有几个像这样的 Javascript 字符串:

var a = "A few sentences. For tests. The point of these sentences is to be used as examples.";
var b = "A couple more sentences. These ones are shorter.";
var c = "Blah. Foo. Bar. Baz. Test. Test 2. Test C.";
var d = "Test sentence.";

我想扩展 string 原型(prototype),使其有一种方法可以将每个字符串拆分为两个字符串的数组,每个字符串的字符数在数学上尽可能相似,同时保持整个句子.

我要寻找的结果:

a.halve() // ["A few sentences. For tests.", "The point of these sentences is to be used as examples."]
b.halve() // ["A couple more sentences.", "These ones are shorter."]
c.halve() // ["Blah. Foo. Bar. Baz.", "Test. Test 2. Test C."]
d.halve() // ["Test sentence.", ""]

如果我执行a.length/2,我会得到两个字符串的理想目标长度...我只是很难split'ing并以正确的顺序加入它们。

最佳答案

首先将所有内容拆分成句子。然后找到最佳位置再次加入。

var a = "A few sentences. For tests. The point of these sentences is to be used as examples.";
var b = "A couple more sentences. These ones are shorter.";
var c = "Blah. Foo. Bar. Baz. Test. Test 2. Test C.";
var d = "Test sentence.";

String.prototype.halve = function() {
const ideaLength = this.length / 2;
const sentences = this.split('.').map(it => it.trim()).filter(it => it != '');
let current = sentences[0].length + 1;
let min = Math.abs(current - ideaLength);
let minPosition = 0;

for (let i = 1; i < sentences.length; i++) {
current = current + 2 + sentences[i].length;
const different = Math.abs(ideaLength - current);

if (different < min) {
min = different;
minPosition = i;
}
}

const first = sentences.slice(0, minPosition + 1).join('. ') + ".";
const second = sentences.slice(minPosition + 1).join('. ') + ".";

return [first, second === "." ? "" : second];
}

console.log(a.halve());
console.log(b.halve());
console.log(c.halve());
console.log(d.halve());

关于javascript - 如何将一串句子分成两半,分成两个字符串的数组,每个字符串的长度尽可能相似?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53643447/

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