gpt4 book ai didi

java - 如何最好地迭代二维数组的对角线

转载 作者:行者123 更新时间:2023-12-05 05:33:06 27 4
gpt4 key购买 nike

我正在写一个单词搜索谜题,我想知道对角线和反对角线定位标语的最佳方法是什么 - 因为现在我已经实现了水平和垂直标语(每个“类型”的标语都是派生的来自父抽象标语),这是搜索将垂直放置的单词的起始索引的代码 - 如果您对此实现有任何提示,请也给我您的反馈:)

public List<Coordinate> findPossiblePositionsForWord(Character[][] grid) {
List<Coordinate> result = new ArrayList<>();
int consecutiveEmptyFields;
final int wordLength = getWord().length();
for (int column = 0; column < grid[0].length; column++) {
consecutiveEmptyFields = 0;
for (int row = grid.length - 1; row >= 0; row--) {
if (grid[row][column] == null) {
consecutiveEmptyFields++;
if (consecutiveEmptyFields >= wordLength) {
result.add(new Coordinate(row, column));
}
} else {
consecutiveEmptyFields = 0;
}
}
}
return result;
}

我能想到的最简单的方法是使用两个 for 循环:从 0 到 x <= word.length 和从 1 到 y <= word.length - 但也许有更好的方法:特别是使用 Java。

进一步说明:对于像这样的标语:"HOKUSPOKUS", "THIS", "GOOGLE", "STRESS", "TEST", "LENGTHY", "PARTLY"我会得到这样的结果(例如 - 它是随机的):

*****************************************
Catchprase successfully added!
Catchprase successfully added!
Catchprase successfully added!
Catchprase successfully added!
Catchprase successfully added!
Catchprase successfully added!
Catchprase successfully added!
*****************************************
G O O G L E _ _ _ H
_ _ _ _ _ _ T _ _ O
_ _ _ _ _ _ H _ _ K
_ _ _ _ _ _ I _ P U
_ _ _ _ _ _ S _ A S
L E N G T H Y _ R P
S T R E S S _ _ T O
_ _ _ _ _ _ _ _ L K
_ _ _ _ _ _ _ _ Y U
T E S T _ _ _ _ _ S

Process finished with exit code 0

现在我也想对角添加标语

最佳答案

我建议不要对每个方向进行特殊封装,而是返回一个方向+起点。这是处理向前、向后、向上、向下以及任一方向的两个对角线的基本思想。

public List<Pair<Coordinate, Coordinate>> findPossiblePositionsForWord(Character[][] grid) {
List<Pair<Coordinate, Coordinate>> result = new ArrayList<>();
final int wordLength = getWord().length();
for (int dirColumn : {-1, 0, 1}) {
for (int dirRow : {-1, 0, 1}) {
if (dirColumn == 0 && dirRow == 0) {
continue;
}
for (
int column = max(0, -dirColumn * wordLength);
column < min(grid.length, grid.length + dirColumn*wordLength);
column++
) {
for (
int row = max(0, -dirRow * wordLength);
row < min(grid.length, grid.length + dirRow*wordLength);
row++
) {
// Test for whether the word can go here...
if (wordCanGoHere) {
result.add(
new Pair(
new Coordinate(row, column),
new Coordinate(dirRow, dirColumn)
)
);
}
}
}
}
}
return result;
}

关于java - 如何最好地迭代二维数组的对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73920047/

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