gpt4 book ai didi

JavaScript 数组除法

转载 作者:行者123 更新时间:2023-11-27 22:53:48 25 4
gpt4 key购买 nike

我正在尝试创建一个递归函数来将数组拼接成两半,直到它的长度只有 3 和 2,而不是将所有这些新数组整齐地放置在一个数组中。

我想我需要一种方法来测量我需要多少个数组,创建它们然后将它们放入我划分的数组中? (我在想 Pow?)。

我正在使用 half 和 Round,因为我在纸上进行了实验,这意味着我最终会得到 2 和 3,而不是除以 3,因为它有时会得到余数 1(我打算使用稍后使用此数据构建三 Angular 测量的相同脚本)。

当前代码(不完整,要使其工作必须继续创建其他 if 语句)。

var pointlist = [];
var pointCount = 666;

var generate = function(t, n) {
for (count = 0; count < n; count++) {
var point = {
x: (Math.random() * 1000),
y: (Math.random() * 1000)
};

t.push(point);
}
}

generate(pointlist, pointCount);
var divisions = [];
var divide = function(a) {
a.sort(function(a, b) {
return a.x - b.x
});
if (a.length > 3) {
b = a.splice(Math.round(a.length / 2), a.length);
divisions.push(a, b);
if (a.length > 3) {
c = a.splice(Math.round(a.length / 2), a.length);
d = b.splice(Math.round(b.length / 2), b.length);
divisions = [];
divisions.push(a, c, b, d);
if (a.length > 3) {
e = a.splice(Math.round(a.length / 2), a.length);
f = c.splice(Math.round(c.length / 2), c.length);
g = b.splice(Math.round(b.length / 2), b.length);
h = d.splice(Math.round(d.length / 2), d.length);
divisions = [];
divisions.push(a, e, c, f, b, g, d, g);
}
}
}
};
divide(pointlist);
console.log(divisions.length + " arrays");
console.log(divisions[0].length + " first length");
console.log(divisions[1].length + " second length");

最佳答案

这是一个递归函数,不包括只应该发生一次的排序:

var pointlist = [];
var pointCount = 666;

var generate = function(t, n) {
for (count = 0; count < n; count++) {
var point = {
x: Math.floor(Math.random() * 1000),
y: Math.floor(Math.random() * 1000)
};

t.push(point);
}
}

generate(pointlist, pointCount);

var divide = function(a) {
a.sort(function(a, b) {
return a.x - b.x
});
function recurseDivide(a) {
if (a.length <= 3) return [a];
var b = a.splice(Math.round(a.length / 2), a.length);
return recurseDivide(a).concat(recurseDivide(b));
}
return recurseDivide(a);
};
var divisions = divide(pointlist);
console.log(divisions.length + " arrays");
console.log(divisions[0].length + " first length");
console.log(divisions[1].length + " second length");</script>

请注意,在调用divide之后,变量pointlist将会发生变化。如果您想避免这种情况,请像这样进行调用:

var divisions = divide(pointlist.slice());

关于JavaScript 数组除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800099/

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