【问题标题】:How to write a recursive algorithm with axis?如何用轴编写递归算法?
【发布时间】:2016-04-14 13:14:56
【问题描述】:

我需要递归地在 x 和 y 轴坐标上找到一个对象。在这个特定的代码中,我需要通过重复调用搜索方法来找到坐标 168,250 中的“Remy”

import java.awt.Point;

public class Sensor {

private Point target;
private Point[] points = {new Point(378, 349), new Point(147, 315), new Point(95, 375), new Point(242, 493), new Point(379, 389), new Point(168, 250), new Point(130, 220), new Point(160, 200), new Point(0, 0), new Point(0, 511), new Point(511, 0), new Point(511, 511)};
private String[] names = {"Bernstein", "DukeDog", "Huey", "Hedwig", "Flipper", "Remy", "QuadCat", "Nemo", "UL", "LL", "UR", "LR"};

public Sensor(String paramString) {
    this.target = new Point(512, 512);
    for (int i = 0; i < this.names.length; i++) {
        if (paramString.equalsIgnoreCase(this.names[i])) {
            this.target = this.points[i];
            break;
        }
    }
}

public static void main(String[] args) {
    Sensor sensor = new Sensor("Remy");
    Point result = sensor.search(0, 0, 512);
    if (result != null) {
        System.out.println("location: " + result.x + "," + result.y);
    } else {
        System.out.println("unable to find");
    }
}

public Point search(int x, int y, int width) {
    //Write a recursive algorithm to find Remy calling the scan method repeatedly such as: scan(x,y,width); 
    //todo 
    return null;
}

public int scan(int paramInt1, int paramInt2, int paramInt3) {
    if ((this.target.x >= paramInt1) && (this.target.x < paramInt1 + paramInt3) && (this.target.y >= paramInt2) && (this.target.y < paramInt2 + paramInt3)) {
        return paramInt3;
    } else {
        return -paramInt3;
    }

}

}

【问题讨论】:

    标签: java recursion axis point binary-search


    【解决方案1】:

    我建议这样做:

    public Point search(int x, int y, int width) {
    
        System.out.println(x + "\t" + y + "\t" + width);
    
        int w = width/2;
        if(w<=1)
            return new Point(x,y); 
        int x1 = x+w;
        int y1 = y+w; 
    
        if(target.x>=x&&target.x<x1&&target.y>=y&&target.y<y1)
            return search(x,y,w); 
        else if(target.x>=x1&&target.x<x+w&&target.y>=y&&target.y<y1)
            return search(x1,y,w); 
        else if(target.x>=x&&target.x<x1&&target.y>=y1&&target.y<y1+w)
            return search(x,y1,w); 
        else /*if(target.x>=x1&&target.x<=x+w&&target.y>=y1&&target.y<=y1+w)*/
            return search(x1,y1,w); 
    }
    

    当你运行这个方法时,输出是:

    0   0   512
    0   0   256
    128 128 128
    128 192 64
    160 224 32
    160 240 16
    168 248 8
    168 248 4
    168 250 2
    location: 168,250
    

    请注意,它假定width 是2 的幂。这很容易适应。

    希望对你有帮助。

    【讨论】:

    • 它回答了你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多