我有一个2d Arraylist (2d Arraylist, myBoard
工作良好,并多次测试正确性),并希望返回列表中相同元素的最长序列。如果我调用myBoard.toString()
,输出看起来像这样:
| 1| 2| 3| 4| 5| 6| 7| 8|
+---+---+---+---+---+---+---+---+
-2 | | | | | | | | |
+---+---+---+---+---+---+---+---+
-1 | | | | | | | | |
+---+---+---+---+---+---+---+---+
0 | | | | | | | | |
+---+---+---+---+---+---+---+---+
1 | A| A| A| | | | | |
+---+---+---+---+---+---+---+---+
2 | | | | | | | | |
+---+---+---+---+---+---+---+---+
3 | | | | | | | | |
+---+---+---+---+---+---+---+---+
4 | | | | | | | | |
+---+---+---+---+---+---+---+---+
5 | | | | | | | | |
+---+---+---+---+---+---+---+---+
6 | B| B| B| B| B| B| | |
+---+---+---+---+---+---+---+---+
7 | | | | | | | | |
+---+---+---+---+---+---+---+---+
8 | C| C| D| C| C| C| C| C|
+---+---+---+---+---+---+---+---+
9 | | | | | | | | |
+---+---+---+---+---+---+---+---+
我知道数组列表从0开始,并且有一些其他的方法来处理这种情况。但我担心的是我的代码不工作,以获得最长的序列从董事会水平。最长的序列在row 6
中,但它返回[(0,1,), (0,1,), (0,2,), (0,2,), (0,5,), (0,5,), (0,6,), (0,6,), (0,7,), (0,7,)]
。为什么返回[(0 1)(0 1)(0,2)(0,2)(0 5)(0 5)(0,6)(0,6)(0 7)(0 7)]? ?
public List<RowAndCol<T>> horizontalSequence(){
ArrayList<RowAndCol<T>> myList = new ArrayList<RowAndCol<T>>();
int max = 1;
int currentCount = 1;
for(int i = 0; i < myBoard.size(); i++){
for(int j = 1; j < myBoard.get(i).size(); j++){
if(myBoard.get(j - 1).equals(myBoard.get(j))){
RowAndCol<T> tempObject1 = new RowAndCol<T>(i, j, myBoard.get(i).get(j));
RowAndCol<T> tempObject2 = new RowAndCol<T>(i, j-1, myBoard.get(i).get(j-1));
myList.add(tempObject1);
myList.add(tempObject2);
currentCount++;
}
else{
if(currentCount > max){
if(currentCount > myList.size()){
max = currentCount;
}
currentCount = 1;
}
}
}
return myList;
}
RowAndCol
类只有一个可以接受(int row, int col, T e)
、getters
和toString()
方法的构造函数
public String toString(){
String result = "";
if(this.e instanceof String){
String element = (String)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
else if(this.e instanceof Integer){
Integer element = (Integer)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
else if(this.e instanceof Character){
Character element = (Character)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
return result;
}
我认为你需要摆脱else
:
if(myBoard.get(j - 1).equals(myBoard.get(j))){
RowAndCol<T> tempObject1 = new RowAndCol<T>(i, j, myBoard.get(i).get(j));
RowAndCol<T> tempObject2 = new RowAndCol<T>(i, j-1, myBoard.get(i).get(j-1));
myList.add(tempObject1);
myList.add(tempObject2);
currentCount++;
}
if(currentCount > max){
myList.clear() // Reset the list to get rid of the old elements
max = currentCount;
currentCount = 1;
}