gpt4 book ai didi

javascript - 如何进行递归调用以查找点数组中元素的总和?

转载 作者:行者123 更新时间:2023-12-01 15:39:44 25 4
gpt4 key购买 nike

这个想法是找到贝塞尔曲线的中点。以下是 De Casteljau 算法,用于找到具有四个点的曲线的中点。
如何使用递归在 javascript 中实现这样的算法?
以下是四个出发点。从这里我们开始算法,通过递归我们到达树的顶端。

(0, 0)
\
(1/2, 0) --> this node is calculated as follows [(x1 + x2)/2, (y1 + y2)/2]
/ \
(1, 0) (3/4, 1/4)
\ / \
(1, 1/2) (3/4, 1/2)
/ \ /
(1, 1) (3/4, 3/4)
\ /
(1/2, 1)
/
(0, 1)
例如点的样本输入将是这样的
const points = [[0,2], [4,5], [6,7], [3,8]]

output = [3,5]

// so the output will be just an array of two numbers for eg: [3,5] (just a rough figure for demo) which represents the midpoint of the above four points obtained by the above algorithm.
这是我尝试过的。但这是完全错误的。有人可以帮忙吗?
    const mid = (array) => {
if (array.length === 1)
return array
else {
array.map(point => [point[0] + point[1] + point[2]])
}
}
更新
请记住,每个节点的计算如下 [(x1 + x2)/2, (y1 + y2)/2]。即,通过取两个相邻点的相似坐标的平均值。=。
更新
Nina Scholz 建议的第二个代码工作正常。
但我想进一步扩展它。 Ninas 代码返回第一个中点。但我想扩展它以找到更多点,如下图所示。
enter image description here

最佳答案

您可以采用递归方法并获得一对。
这种方法只采用整数值。

const
getB = array => {
if (array.length === 1) return array[0];

const result = [];

for (let i = 1; i < array.length; i++) {
result.push([Math.floor((array[i - 1][0] + array[i][0]) / 2), Math.floor((array[i - 1][1] + array[i][1]) / 2)]);
}

return getB(result);
},
points = [[0, 2], [4, 5], [6, 7], [3, 8]];

console.log(getB(points));

不使用整数值的相同方法。

const
getB = array => {
if (array.length === 1) return array[0];

const result = [];

for (let i = 1; i < array.length; i++) {
result.push([(array[i - 1][0] + array[i][0]) / 2, (array[i - 1][1] + array[i][1]) / 2]);
}

return getB(result);
},
points = [[0, 2], [4, 5], [6, 7], [3, 8]];

console.log(getB(points));

关于javascript - 如何进行递归调用以查找点数组中元素的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63365732/

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