【问题标题】:the classic algorithm to find orientation of three points is wrong?寻找三点方向的经典算法是错误的?
【发布时间】:2018-03-27 08:18:14
【问题描述】:

算法可以参考这里(http://algs4.cs.princeton.edu/91primitives/)和这里(http://www.geeksforgeeks.org/orientation-3-ordered-points/),

试试下面的代码 p1 = {0, 0}, p2 = {4, 4}, p3 = {0, 3}, or p1 = {0, 0}, p2 = {4, 4}, p3 = {0, 5},我认为这两种情况都应该是顺时针,但算法输出逆时针。

// A C++ program to find orientation of three points
#include <iostream>
using namespace std;

struct Point
{
    int x, y;
};

// To find orientation of ordered triplet (p1, p2, p3).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p1, Point p2, Point p3)
{
    // See 10th slides from following link for derivation
    // of the formula
    int val = (p2.y - p1.y) * (p3.x - p2.x) -
            (p2.x - p1.x) * (p3.y - p2.y);

    cout << val << endl;
    if (val == 0) return 0; // colinear

    return (val > 0)? 1: 2; // clock or counterclock wise
}

// Driver program to test above functions
int main()
{
    Point p1 = {0, 0}, p2 = {4, 4}, p3 = {0, 3};
    int o = orientation(p1, p2, p3);
    if (o==0)        cout << "Linear";
    else if (o == 1) cout << "Clockwise";
    else             cout << "CounterClockwise";
    return 0;
}

【问题讨论】:

  • (0,0) -> (4, 4) -> (0, 3) 在我看来是逆时针方向。
  • 是的,@serhiyb,你可以试试我的代码,它会逆时针输出。
  • 哪个是正确答案。那么你的问题是什么?
  • (0,0) -> (4,4) -> (0, 3) 是逆时针方向。算法逆时针输出。完美的一对!你的第二个例子也是如此。
  • @serhiyb,对不起,我之前误读了您的 cmets。为什么你认为这是逆时针明智的?我认为这是顺时针。

标签: c++ algorithm geometry computational-geometry


【解决方案1】:

让我们画出序列(0, 0) -&gt; (4, 4) -&gt; (0, 3)

如您所见,它是逆时针方向的。这样代码就可以正常工作了,你只是判断错误。

【讨论】:

  • 谢谢,我想我在这种情况下对逆时针方向的理解有些错误,通过您的示例图,我明白了,将您的回复标记为答案。
【解决方案2】:

顺时针或逆时针取决于您的轴方向!

真正重要的是三角形测试对对齐的点给出 0,一侧为正,另一侧为负。

只要拿一个测试用例,你就会永远知道什么是正确的“签名”。

【讨论】:

  • 根据经验,经典算法是正确的。
猜你喜欢
  • 2023-03-15
  • 2021-08-25
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2010-10-24
  • 2010-12-23
  • 1970-01-01
  • 2012-04-29
相关资源
最近更新 更多