【发布时间】:2022-11-02 16:10:54
【问题描述】:
首先,我们有两个坐标为 x, y, z 的点:start(0, 0, 0) 和随机生成的 r(x, y, z),其中 x, y, z 是从 0 到 100 的随机整数。
有一个函数(已经由我编写)计算起点和 r 之间的距离。
我需要编写另一个仅将距离作为参数的函数。我们需要使用起始点内的不同坐标调用第一个函数(改变点之间的距离),直到找到 r 的坐标(即距离应该等于 0)。
在这种情况下,最好的算法是什么?
我的第一部分代码包括计算距离的函数:
const r = [];
for (let i = 0; i < 3; i++) {
r.push(Math.floor(Math.random() * 100) + 1); // Generating random r point
}
const s = [0, 0, 0];
let distance;
function calculateDistance(random, myPoint) {
distance = Math.abs(
Math.floor(
Math.sqrt(
Math.pow((random[0] - myPoint[0]), 2) +
Math.pow((random[1] - myPoint[1]), 2) +
Math.pow((random[2] - myPoint[2]), 2)
)
)
);
return distance;
}
接下来我做了以下事情:
function searchPoint(distance) {
let min = 173, // biggest possible distance if r(100, 100, 100)
tempArr = [],
closePoints = [],
prev;
for (let i = 0; i < s.length; i++) {
while (s[i] < 100) { // For x, y, z of start point I go through every possible value
prev = min; // Keep track on previos min value
if (min > distance) {
min = distance;
}
if (prev < distance) { // If the distance increases it means we're drifting away from needed coordinates
break;
}
tempArr.push({distance, point: s[i]}); // Here I save pairs distance-coordinate
s[i]++;
distance = calculateDistance(r, s);
}
closePoints.push(tempArr.filter(obj => obj.distance === min)); // For each of 3 coordinates I leave only minimal values, but the thing is there are several of them
tempArr = [];
min = 173;
}
let mappedPoints = closePoints.map(arr => {
let mid = Math.floor((arr.length - 1) / 2); // So as a solution I try to pick up middle element from an array of points close to the needed one (which works most of the time BUT*)
return arr[mid];
});
console.log(mappedPoints);
mappedPoints.forEach((obj, i) => s[i] = obj.point);
console.log(s);
console.log(calculateDistance(r, s));
if (calculateDistance(r, s) === 0) { // We check up on the distance and it's only logical that if it's equal to 0 - we found the point
console.log('Point was found!!!');
}
- 但是!在边界值(比如 <14 和 >86)中,closePoints 数组中所需的点不会在中间(例如,2/5/94/98) 此外,在 [3, 45, 93] 之类的情况下,这样的点可能不止一个。 所以这是我卡住的部分......
【问题讨论】:
-
仅给定与原点的距离,如何确定点?那是一个圆的图形,而不是一个点。
-
你尝试过哪些算法?您应该在帖子中包含所有相关功能,最好是作为 sn-p。
-
一个球的图形
-
我认为这里可能有一个有趣的问题,但问题设置尚不清楚。你能添加一个例子或插图吗?
-
伙计们,我更新了问题,请看一下
标签: javascript algorithm geometry coordinates