let input = [
[[1, 4], [40, 4]],
[[1, 5], [40, 5]],
[[4, 7], [4, 24]],
[[1, 9], [4, 1]],
[[1, 2], [6, 4]],
[[80, 4], [90, 4]],
[[4, 1], [4, 40]],
[[4, 35], [4, 29]],
[[4, 28], [4, 35]],
[[5, 3.6], [9, 5.2]],
]; // Input
Output = [
[[[1, 4], [40, 4]], [[80, 4], [90, 4]]],
[[[1, 5], [40, 5]]],
[[[4, 7], [4, 24]], [[4, 1], [4, 40]]],
[[[4, 35], [4, 29]], [[4, 28], [4, 35]]],
[[[1, 9], [4, 1]]],
[[[1, 2], [6, 4]], [[5, 3.6], [9, 5.2]]],
];
如果给定一条线的每个起始和结束坐标的系列输入,例如 [[1,4],[40,4]] 意味着它有 2 个点连接 [1,4] 和 [40 ,4] 形成一条直线。我现在的目标是将共享相同方程 y=mx+c 的所有线组合在一起,形成一个嵌套数组,如上所示。例如,
[[1,4],[40,4]] and [[80,4],[90,4]] share the same linear equation y=4
[[4,7],[4,24]],[[4,1],[4,40]] share the same linear equation x=4
[[1,2],[6,4]] and [[5,3.6],[9,5.2]] share the same linear equation y=0.4x+1.6
[[1,9],[4,1]] is alone and it has the linear equation of -2.67x+11.67
Here is my working codepen demo
我知道如何编码以找到 y=mx+c 中的 m 和 c,但问题是例如 [[4,7],[4,24]] 和 [[4,1] ,[4,40]],m梯度变为无穷大,无解。
任何人都可以指导我如何获得正确的输出吗?
最佳答案
您可以计算每组点的斜率方程并将其分配给每个数组项,然后分组:
const input=[[[1,4],[40,4]],[[1,5],[40,5]],[[4,7],[4,24]],[[1,9],[4,1]],[[1,2],[6,4]],[[80,4],[90,4]],[[4,1],[4,40]],[[4,35],[4,29]],[[4,28],[4,35]],[[5,3.6],[9,5.2]]];
const inputsWithSlope = input.map((points) => {
const [[x, y], [x1, y1]] = points;
const slope = (y1 - y) / (x1 - x)
const b = y1 - slope * x1
return {
points,
line: x1 == x ? `x = ${x}` : `y = ${slope}x + ${b}`
}
})
const res = inputsWithSlope.reduce((acc, curr) => {
const accProp = acc[curr.line]
acc[curr.line] = !accProp ? [curr.points] : [...accProp, curr.points]
return acc
}, {})
const result = Object.values(res)
result.forEach(e => console.log(JSON.stringify(e)))
要处理舍入问题,您必须对其进行舍入:
const input=[[[1,4],[40,4]],[[1,5],[40,5]],[[4,7],[4,24]],[[1,9],[4,1]],[[1,2],[6,4]],[[80,4],[90,4]],[[4,1],[4,40]],[[4,35],[4,29]],[[4,28],[4,35]],[[5,3.6],[9,5.2]]];
const inputsWithSlope = input.map((points) => {
const [[x, y], [x1, y1]] = points;
const slope = (y1 - y) / (x1 - x)
const b = y1 - slope * x1
return {
points,
line: x1 == x ? `x = ${x}` : `y = ${slope.toFixed(2)}x + ${b.toFixed(2)}`
}
})
const res = inputsWithSlope.reduce((acc, curr) => {
const accProp = acc[curr.line]
acc[curr.line] = !accProp ? [curr.points] : [...accProp, curr.points]
return acc
}, {})
const result = Object.values(res)
result.forEach(e => console.log(JSON.stringify(e)))
关于javascript - 将同一线性方程的所有直线分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75380481/