【问题标题】:Java recursion parametersJava 递归参数
【发布时间】:2018-06-12 20:30:12
【问题描述】:

我的作业被困住了;有人有想法吗?

任务: 实现一个递归方法 boxed(double[] center, double radius) 绘制如下图:

(外部正方形是图像边缘。)数组中心包含所有正方形中心的 x 和 y 坐标,而半径是正方形长度的一半。内部正方形总是旋转 45°。当半径小于一个像素时,该方法应该停止绘制。

给出了其他方法。 这个画了一个双角旋转的正方形:

private static void squareRotated(double[] center, double radius, double angle) {
        double[] upperLeft = {-radius, radius};
        double[] upperRight = {radius, radius};
        double[] lowerLeft = {-radius, -radius};
        double[] lowerRight = {radius, -radius};


        double[] rotUpperLeft = rotatePoint(upperLeft,angle);
        double[] rotUpperRight = rotatePoint(upperRight,angle);
        double[] rotLowerLeft = rotatePoint(lowerLeft,angle);
        double[] rotLowerRight = rotatePoint(lowerRight,angle);


        StdDraw.polygon(new double[]{rotUpperLeft[0]+center[0],rotUpperRight[0]+center[0],
                        rotLowerRight[0]+center[0],rotLowerLeft[0]+center[0]},
                        new double[]{rotUpperLeft[1]+center[1],rotUpperRight[1]+center[1],
                        rotLowerRight[1]+center[1],rotLowerLeft[1]+center[1]});
    }

这个将一个点旋转双角:

private static double[] rotatePoint(double[] point, double angle) {
        double[] result = new double[2];
        result[0] = point[0]*Math.cos(angle) - point[1]*Math.sin(angle);
        result[1] = point[0]*Math.sin(angle) + point[1]*Math.cos(angle);
        return result;
    }
}

这是我的代码:

private static double angle = 0;

    private static void boxed(double[] center, double radius) {
        if (radius > (double) 1/512) {
            squareRotated(center, radius, angle);
            angle += Math.PI/4;
            boxed(center, Math.sqrt(radius*radius + radius*radius)/2);
        }
    }

它有效,但有没有办法可以避免私有静态双角?我不允许在方法中添加第三个参数,我必须通过递归来解决它。

【问题讨论】:

  • 这样的声音应该在 CodeReview 上...
  • 我投票结束这个问题,因为它属于Code Review

标签: java function recursion graphic


【解决方案1】:

这里的正常技术是有一个public 方法公开API,然后调用private 方法来实际执行递归过程,将初始条件传递给它。

// The private one that actually does the recursive process.
private static void boxed(double[] center, double radius, double angle) {
    if (radius > 1.0 / 512.0) {
        squareRotated(center, radius, angle);
        angle += Math.PI / 4.0;
        boxed(center, Math.sqrt(radius * radius + radius * radius) / 2.0, angle);
    }

}

// The public one to provide the API.
public static void boxed(double[] center, double radius) {
    boxed(center, radius, 0.0);
}

注意:我没有检查过这段代码——这只是为了演示这项技术。

【讨论】:

  • 谢谢,但恐怕我不允许这样做。我只需要实现一种方法。
  • @Leila - 你确定吗?在我看来,这似乎是一个非常适得其反的练习,除非他们希望你在下一个作业中看到这种技术如何更好地发挥作用,因为他们允许你使用两种方法。
  • 我想是的...否则任务描述中会有提示。还有其他解决办法吗?
猜你喜欢
  • 1970-01-01
  • 2015-02-20
  • 2016-07-22
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
相关资源
最近更新 更多