एक लाइन सेगमेंट की लंबाई x पर n समान दूरी के पॉइंट्स जनरेट करने के लिए, सेगमेंट को n+1 बराबर भागों में बांटें और प्रत्येक विभाजन बिंदु की गणना करें।
गणितीय सूत्र
पॉइंट i (1 से n तक) की स्थिति: position = (i / (n + 1)) * length
फंक्शन कार्यान्वयन
function generateEquidistantPoints(n, length) {
const points = [];
for (let i = 1; i <= n; i++) {
// i को (n+1) से विभाजित करके अनुपात प्राप्त करें, फिर लंबाई से गुणा करें
const position = (i / (n + 1)) * length;
points.push(Math.round(position)); // पूर्णांक के लिए राउंड करें
}
return points;
}
// उपयोग
const points = generateEquidistantPoints(5, 50);
console.log("पॉइंट्स:", points);
आउटपुट
पॉइंट्स: [ 8, 17, 25, 33, 42 ]
व्याख्या (n=5, length=50 के लिए)
| i | सूत्र | गणना | राउंडेड |
|---|---|---|---|
| 1 | (1/6) × 50 | 8.33 | 8 |
| 2 | (2/6) × 50 | 16.67 | 17 |
| 3 | (3/6) × 50 | 25.00 | 25 |
| 4 | (4/6) × 50 | 33.33 | 33 |
| 5 | (5/6) × 50 | 41.67 | 42 |
उन्नत संस्करण: फ्लोटिंग पॉइंट प्रिसिजन के साथ
function generatePrecisePoints(n, length, decimals = 2) {
const points = [];
const factor = Math.pow(10, decimals);
for (let i = 1; i <= n; i++) {
const position = (i / (n + 1)) * length;
// निर्दिष्ट दशमलव स्थानों तक राउंड करें
points.push(Math.round(position * factor) / factor);
}
return points;
}
console.log(generatePrecisePoints(5, 50, 2));
// [ 8.33, 16.67, 25, 33.33, 41.67 ]
2D/3D निर्देशांकों के लिए विस्तार
function generatePointsOnLine(start, end, n) {
const [x1, y1] = start;
const [x2, y2] = end;
const points = [];
for (let i = 1; i <= n; i++) {
const t = i / (n + 1);
const x = x1 + t * (x2 - x1);
const y = y1 + t * (y2 - y1);
points.push([x, y]);
}
return points;
}
// (0,0) से (100,100) तक 3 पॉइंट्स
console.log(generatePointsOnLine([0, 0], [100, 100], 3));
// [ [25, 25], [50, 50], [75, 75] ]
चलाने का तरीका
node equidistant-points.js