gpt4 book ai didi

java - 无限二维数组搜索

转载 作者:行者123 更新时间:2023-12-02 10:36:58 25 4
gpt4 key购买 nike

我正在尝试实现一种不允许棋子跳过另一个棋子的方法。 IntelliJ 告诉我这个方法总是返回反转,但我看不到问题。谁能帮我吗?我使用二维数组作为棋盘。 xFrom yFrom 是棋子要移动的坐标,xTo yTo 是棋子要移动到的坐标

 public boolean pieceJumps(char[][] boardIn, int xFrom, int yFrom, int xTo, int yTo) {
for (int i = 0; i < boardIn.length; i++) {
for (int j = 0; j < boardIn[i].length; j++) {
if (boardIn[i][j] != FREE && (Math.sqrt(Math.pow((i - xFrom), 2) + Math.pow((j - yFrom), 2)) < (Math.sqrt(Math.pow((xTo - xFrom), 2) + Math.pow((yTo - yFrom), 2))))) {
//IF THE DISTANCE MAGNITUDE OF A POINT FROM THE PIECE TO BE MOVED LANDS ON A SPACE WITH ANOTHER PIECE BUT IS SMALLER IN MAGNITUDE THAN THE DISTANCE TO VE MOVED, RETURNS TRUE THAT PIECE WOULD JUMP


return true;
} else {
return false;
}

}
}
return false;
}
}

最佳答案

你的循环最多有一次迭代,原因是 return 语句。

您的条件语句也有一些问题。如何知道要检查哪个方 block ?使用当前的循环结构,您将需要计算该部件需要行进的 vector ,并检查沿着该路径落下的 vector 。

return 语句将退出函数的循环和步出。 else return false 没问题,如果空间被占用,你希望它失败。你的 if 条件语句需要更多。仅当您到达目的地时才应返回 true,如果第一个槽位空闲则返回 true。

尚未验证逻辑,这也不是最有效的方法,但这是朝着正确方向迈出的一步。我根据类职责分解了代码,类职责基于基于组合的设计。 https://www.geeksforgeeks.org/composite-design-pattern/ 。基本上打破了基于任务概念的逻辑,其中每个类都有一个要实现的特定目标。这使得调试、理解和扩展项目变得更加容易。

public class Board {
public boolean pieceJumps(char[][] boardIn, int xFrom, int yFrom, int xTo, int yTo) {
Line line = new Line(xFrom, yFrom, xTo, yTo);

for (int i = 0; i < boardIn.length; i++) {
for (int j = 0; j < boardIn[i].length; j++) {
// If Point exists on line then validate position
if (line.existsOnLine(i, j)) {
// If the point we are on is already occupied fail
if (boardIn[i][j] != 'o') {
return false;
} else {
// If we are where we want to be
if (i == xTo && j == yTo) {
boardIn[i][j] = 'x';
return true;
}

// continue to next if we haven't reach destination
}
}
}
}
return false;
}
}

/**
* Defines basic line properties and calculations
*/
public class Line {
private int b;
private int slope;

/**
* Constructor which accepts two points
* @param x1
* @param y1
* @param x2
* @param y2
*/
public Line(int x1, int y1, int x2, int y2) {
calculateSlope(x1, y1, x2, y2);
calculateB(x1, y1);
}

/**
* Does point exist on line
* @param x
* @param y
* @return true if on line else false
*/
public boolean existsOnLine(int x, int y) {
return y == (slope * x) + b;
}

///
// PRIVATE HELPER METHODS
///

/**
* Determine line slope
* @return slope of line
*/
private void calculateSlope(int x1, int y1, int x2, int y2) {
slope = (x2 - x1) / (y2 - y1);
}

/**
* Calculate y-intercept for line
* @param x
* @param y
*/
private void calculateB(int x, int y) {
b = y - slope * x;
}
}

关于java - 无限二维数组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com