【问题标题】:How do I compare objects based on their location on a line如何根据对象在一条线上的位置比较对象
【发布时间】:2011-04-15 14:16:08
【问题描述】:

我正在尝试编写一个比较方法来执行此操作。

// If a and b lie on the same horizontal line, 
//    then a < b when a is to the left of b
// Otherwise, a < b when a is below b   

我真的不知道该怎么做,通常我只是比较如果 a>b 返回 +ve int 和 -ve int 如果小于或等于 0。

根据您的建议我的解决方案......

我使用了 Jim Blackler、Ralph 和 Peter Lawrey 的想法并提出了这个想法。很抱歉,我有点困惑,没有想到笛卡尔坐标感谢 Aasmund Eldhuset,这是我最后的比较方法.. 它有效

类词典实现比较器{ //这需要重写所以...
// 如果 a 和 b 在同一水平线上, // 那么当 a 在 b 的左边时 a 时 a

    }
    else 
        return 0;
}

}

【问题讨论】:

  • 行什么?您如何存储对象所在的行?事先不知道怎么回答?
  • “在同一行”是什么意思,它们是在一个数组中吗? line 是那些对象的成员吗?

标签: java


【解决方案1】:

你的意思是喜欢

class Point implements Comparable<Point> {
  double x,y;

  public int compareTo(Point b) {
      // If a and b lie on the same horizontal line, 
      if (y == b.y)
      //    then a < b when a is to the left of b
          return x < b.x ? -1 : x > b.x ? +1 : 0;
      // Otherwise, a < b when a is below b
      return y < b.y ? -1 : y > b.y ? +1 : 0;
  }
}

【讨论】:

  • implements Comparable&lt;Point&gt; ?
  • @Dave Costa,一个明智的补充,但不是必需的。我现在补充。 ;)
【解决方案2】:

对于可以比较的任何类型 a 和 b,您都需要一个类属性。一旦你开始更具体地思考,这很容易。

a 和 b 的类型是什么?

【讨论】:

    【解决方案3】:
    if (a.y == b.y) {
      return a.x < b.x;
    } else {
      return a.y < b.y;
    }
    

    【讨论】:

      【解决方案4】:

      从文本中,听起来ab 是笛卡尔坐标(每个都有一个x 和一个y 值)。你有一个代表坐标的类吗?如果没有,你应该做一个,并且 compare 方法应该接受该类的两个实例,你可以使用它们的 xy 值来确定它们是否在同一水平线,或者哪一条在另一条的左边。

      【讨论】:

        【解决方案5】:

        在java中实现比较方法的一种方法是Comparable Interface

        它只有一种方法int compareTo(T o)。此方法将此对象(调用该方法的对象)与指定对象 (b) 进行比较。返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。

        假设对象是 Pseudo 类(因为它只是伪代码),那么 compare 方法应该是这样的。

        class Pseudo implements Comparable<Pseudo> {
        
           @Override
           int compareTo(Pseudo b) {
        
             if (this and b lie on the same horizontal line) {
                if (this is to the left of b) {
                   return -1;
                } else {
                  return 1;
                }
              } else {
                 if (this is to the below of b) {
                   return -1;
                 } else {
                    return 1;
                 }
              }
           }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多