我必須做一個算法,用隨機(0到2)數字填充二維數組,唯一的條件是我可以在水平和垂直方向上有相同的數字3次或更多次。 例如爲什麼我的算法返回stackoverflow異常?
[0,0,1,2,1
0,1,2,1,2
1,2,0,1,0]
是確定
[0,0,0,2,1
0,1,2,1,2
1,2,0,1,0]
或
[0,0,1,2,1
0,1,1,1,2
1,2,1,1,0]
是錯誤的。
因此,這裏是我的算法:
public class CandyHelper {
private final int minimumChainLength = 3;
private final int searchChainSize = 3;
public Candy[][] randomInit(int rowCount, int columnCount) {
Candy[][] map = new Candy[rowCount][columnCount];
for (int row = 0; row < rowCount; ++row) {
for (int column = 0; column < columnCount; ++column) {
// Fill square with random candy.
Random rand = new Random();
int value = rand.nextInt(3);
Candy candy = new Candy();
candy.setType(value);
map[row][column] = candy;
}
}
if (findHint(map)) {
//System.out.println("Winning conditions");
map = null;
map = randomInit(rowCount, columnCount);
} else {
System.out.println("no wining");
}
return map;
}
// Function which searches for match of at least `MinimumChainLength`.
private boolean findHint(Candy[][] map) {
int rowCount = map.length;
int columnCount = map.length;
List<Candy> hintMove = new ArrayList<Candy>();
// Search rows.
for (int row = 0; row < rowCount; ++row) {
// Search for chain.
for (int chainStart = 0; chainStart < columnCount - searchChainSize; ++chainStart) {
// Add initial cell in chain.
hintMove.clear();
hintMove.add(map[row][chainStart]);
for (int nextInChain = chainStart + 1; nextInChain < columnCount; ++nextInChain) {
if (map[row][nextInChain].getType() == hintMove.get(0).getType()) {
hintMove.add(map[row][nextInChain]);
} else {
break;
}
}
// Was a chain found?
if (hintMove.size() >= minimumChainLength)
return true;
}
}
// Search columns.
for (int column = 0; column < columnCount; ++column) {
// Search for chain.
for (int chainStart = 0; chainStart < rowCount - searchChainSize; ++chainStart) {
// Add initial cell in chain.
hintMove.clear();
hintMove.add(map[chainStart][column]);
for (int nextInChain = chainStart + 1; nextInChain < rowCount; ++nextInChain) {
if (map[nextInChain][column].getType() == hintMove.get(0).getType()) {
hintMove.add(map[nextInChain][column]);
} else {
break;
}
}
// Was a chain found?
if (hintMove.size() >= minimumChainLength)
return true;
}
}
// No chain was found, so clear hint.
hintMove.clear();
return false;
}
}
和我的POJO:
public class Candy {
private int type;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "Candy{" + "type=" + type + '}';
}
}
當我從10×10陣列我開始越來越堆棧溢出錯誤開始。 我應該怎麼做才能糾正它們?
在此先感謝。
請發佈整個堆棧跟蹤 – Frakcool
堆棧溢出將使我尋找一種方法,一次又一次地調用自己,添加更多的幀到堆棧,直到它耗盡。找那個。 (PS - 「糖果」?這對你的上下文有意義嗎?) – duffymo
不是問題所在,但你不想爲你生成的每個數字創建一個新的隨機數。 – John3136