查看: 1624| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

[入门|算法|数据结构] 算法4 week3 slopeOrder函数求助

全局:
公开课
学校名称: 普林斯顿
Unit号: 3
开课时间: 2017-07-05
课程全名: Algorithm4
平台: Coursera

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
/**
     * Compares two points by the slope they make with this point.
     * The slope is defined as in the slopeTo() method.
     *
     * @return the Comparator that defines this ordering on points
     */
    public Comparator<Point> slopeOrder() {

        return null;
        /* YOUR CODE HERE */
    }
week3里面要完成这个slopeOrder函数,这里面要求比较两个点的斜率,可是并没有传点的参数进来啊,我看了一下网上的代码,是建了一个slopeOrder的子类,在子类里面要求传参数进去,有点看不懂。
    private class SlopeOrder implements Comparator<Point> {
        public int compare(Point q1, Point q2) {
            double d1 = slopeTo(q1);
            double d2 = slopeTo(q2);
            if (d1 == d2) return 0;
            if (d1 < d2) return -1;
            return +1;
        }
    }
public Comparator<Point> slopeOrder() {
        return new SlopeOrder();
    }
调用slopeOrder的时候没有参数传入,那新建的类里面也没有参数,那compare函数是怎么调用的呢?

上一篇:Stanford Algorithms Specialization
下一篇:mooc 课调查
🔗
magicsets 2017-7-5 04:17:26 | 只看该作者
全局:
本帖最后由 magicsets 于 2017-7-5 04:26 编辑

这个代码用起来是这样的:
----
Comparator<Point> o = slopeOrder();

Point p1 = /* some point */;
Point p2 = /* some point */;
int value = o.compare(p1, p2);
----

也就是slopeOrder()返回的o是一个“比较器”,本质上是一段“代码”而不是一段“数据”。然后别人再用这段代码去比较两个点。

如果想深入理解的话可以去了解一下“高阶函数”(high-order function),“闭包”(closure)这些概念。
回复

使用道具 举报

🔗
ilvfruits 2017-12-5 12:48:02 | 只看该作者
全局:
没看懂啊,这段代码应该怎么写?我写的如下没法通过compile,就是说compare(Point p1, Point p2)方法出错,求指教
public Comparator<Point> slopeOrder() {
// compare two points by slopes they make with this point
@Override
public int compare(Point p1, Point p2) {
double slopeP1 = slopeTo(p1);
double slopeP2 = slopeTo(p2);
if (slopeP1 == slopeP2) return 0;
if (slopeP1 < slopeP2) return -1;
else return +1;
}
}

错误是:
Error: Syntax error on token "(", ; expected
Error: Syntax error on token ",", ; expected
Error: Syntax error on token ")", ; expected
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表