递归方法 - 标尺刻度线

时间:2013-10-22 02:54:01

标签: java methods recursion

今天我正在研究一种递归方法,将刻度标记放在标尺上。作业说要放置刻度线并打印其高度和位置。假设x& y为(0,0),宽度为20,高度为10,程序应显示类似的内容

中间刻度线 - 位置10,高度10
位置5,高度5
位置2.5,高度2.5
位置7.5,高度2.5
位置15.0,高度5.0
位置12.5,高度2.5
位置17.5,高度2.5

注意允许的最小高度为2.00,每个位置是较大高度的一半。我尝试了很多东西,我有点想法,但是没有用。我从第10位到第7.5位获得了数字,但右侧是一团糟,即使只是移动x坐标。这是我的代码,希望你能帮助我,谢谢你。

*main method contains the input for user and the method calls.
        DrawRulerLeft(x,y,width,height);     //Method to draw left part of rule
        DrawRulerRight(x,y,width,height);   //Method to draw right part of rule

public static void DrawRulerLeft(double x, double y, double w, double h) {

  if (h > 2 ) {  //smallest height aloud
        w = w/2;  
        System.out.println("Tick position:+ w + " Tick height: " + h );
        DrawRulerLeft(x, y, w, h/2);
 } 
 }

//Recursive method to draw right of rule
 public static void DrawRulerRight(double x, double y, double w, double h) {

     if (h > 2 && w >= 0) {
        DrawRulerRight(x+w/2,y,w/2,h/2); 
        System.out.println("Tick position:" + x + " Tick height: " + h );
         }

    }

3 个答案:

答案 0 :(得分:2)

基本上你只需要考虑到,只要有一个划分器,就有一个+和一个 - 置换。忽略标尺范例的左侧/右侧,因为每个分区只有左侧/右侧。

drawTicks(20, 20, 20);

public static void drawTicks(double h, double tick, double pos) {

    System.out.println("tick: " + tick + " pos: " + pos);

    if (tick / 2 >= 2) {

        if (tick != h) {
            drawTicks(h, tick / 2, pos + tick / 2);
        }

        drawTicks(h, tick / 2, pos - tick / 2);
    }

}

输出以下内容:

tick: 20.0 pos: 20.0
tick: 10.0 pos: 10.0
tick: 5.0 pos: 15.0
tick: 2.5 pos: 17.5
tick: 2.5 pos: 12.5
tick: 5.0 pos: 5.0
tick: 2.5 pos: 7.5
tick: 2.5 pos: 2.5

答案 1 :(得分:1)

类似于两半的二进制遍历,尝试这种方法: -

//Recursive method to draw 
private static void DrawRulerRecursive(double w, double h) {
  if (h > 2) {
    System.out.println("Tick position:" + w + " Tick height: " + h);
    DrawRuler(w+w/2,h/2);
    DrawRuler(w-w/2,h/2);
  }
}

public static void DrawRuler(int w, int h) {
   double mid = (0 + w)/2; // Range: (0:20), Mid: 10
   DrawRulerRecursive(mid, h);
}

问题类似于建立一个BST,其中tick的高度在降低水平时减半。我的建议是深度优先顺序遍历,但你也可以使用广度优先遍历。

答案 2 :(得分:1)

基本操作是在间隔中间绘制高度height的刻度。现在xy以及width未定义,这是作业,因此我将使用其他符号。假设给出的间隔是(a, b)

因此方法签名可以是void drawTick(double a, double b, double height)

该方法的第一行可以测试基本情况,这与高度至少为2有关。没有无限递归调用,谢谢!

if(height < 2) return;

下一行可以“画出”刻度线。

System.out.println("Tick position:"+ (a+b)/2 + " Tick height: " + height );

现在从这个设置中你可以弄清楚接下来需要做些什么来绘制一半高度的所有刻度。

相关问题