我正在尝试创建一个递归函数,将数组拼接成两半,直到它只有3和2的长度,而不是将所有这些新数组整齐地放在数组中。
我想我需要一种方法来测量我需要多少个数组,创建它们然后将它们放入我的分割数组中? (我在想Pow?)。
我正在使用half和Round,因为我在纸上进行了实验,这意味着我将以2和3结束,而不是除以3,因为它有时会得到1的余数(我打算使用以后用这个数据构建三角剖分的相同脚本。)
当前代码,(不完整,为此工作必须继续创建其他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");
答案 0 :(得分:1)
这是一个递归函数,不包括只应该发生一次的排序:
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());
答案 1 :(得分:0)
不是递归的,但是在名为Array.prototype.bisect()
的无用数组方法的帮助下,您可以执行以下操作;
Array.prototype.bisect = function(){
var atIndex = Math.round(this.length/2);
return [this.slice(0,atIndex),this.slice(atIndex)];
};
var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],
brr = [];
function breakUp(arr){
while (arr[0].length > 3) arr = [].concat(...arr.map(a => a.length > 3 && a.bisect()));
return arr;
}
brr = breakUp([arr]);
console.log(JSON.stringify(brr));