我想发送我的Arraylist:
ArrayList<Tile> myList = new ArrayList<Tile>();
之后:
public void shuffleBoard() {
Collections.shuffle(myList);
for (int i = 0; i < SIZE; i++) {
}
switch (SIZE) {
case 0:
moveEmptyTile(Direction.UP);
case 1:
moveEmptyTile(Direction.DOWN);
case 2:
moveEmptyTile(Direction.LEFT);
case 3:
moveEmptyTile(Direction.RIGHT);
}
看起来像这样:
[[ 05 ], [ 12 ], [ ** ], [ 08 ], [ 02 ], [ 03 ], [ 01 ], [ 10 ], [ 04 ], [ 11 ], [ 07 ], [ 15 ], [ 13 ], [ 09 ], [ 06 ], [ 14 ]]
我想发送到一个数组,所以我可以通过这段代码检查该板是否可以解决:
public static boolean isSolvable(int[] state){
//prepare the mapping from each tile to its position
int[] positions = new int[16];
for(int i = 0; i < state.length; i++){
positions[state[i]] = (i+1)%16;
}
//check whether this is an even or odd state
int row = (positions[0]-1)/4;
int col = (positions[0]-1)-row*4;
boolean isEvenState = positions[0] == 0 || row % 2 == col %2;
//count the even cycles
int evenCount = 0;
boolean[] visited = new boolean[16];
for(int i = 0; i < positions.length; i++){
if(visited[i])
continue;
//a new cycle starts at i. Count its length..
int cycleLength = 0;
int nextTile = i;
while(!visited[nextTile]){
cycleLength++;
visited[nextTile] = true;
nextTile = positions[nextTile];
}
if(cycleLength % 2 == 0)
evenCount++;
}
return isEvenState == (evenCount % 2 == 0);
所以我想将Arraylist
转换为Array
,并将其作为
int[] state
到isSolvable(int[] state)
,以便检查我的拼图是否可以解决。
这可能是愚蠢的简单,但尝试后我的头是果冻 搜索此论坛以寻求解决方案。
我的瓷砖课程:
public class Tile {
private int value;
private static int maxValue = 15;
private static int minValue = 0;
public Tile(int value) {
setValue(value);
}
public int getValue() {
return value;
}
public void setValue(int value) {
if (value <= maxValue)
this.value = value;
else if (value > maxValue)
System.err.print("To high");
}
public boolean isEmpty() {
if (getValue() == minValue) {
return true;
} else {
return false;
}
}
@Override
public String toString() {
if (this.isEmpty() == true) {
return "[ ** ]";
}
if (this.value < 10) {
return "[ 0" + value + " ]";
}
else {
return "[ " + value + " ]";
}
}
}
真诚的。
答案 0 :(得分:1)
一般方法是使用循环构建int
数组,同时将每个Tile
转换为int
(我想你想提取value
字段) :
int size = myList.size();
int[] values = new int[size];
for (int i = 0; i < size; i++) {
values[i] = myList.get(i).getValue();
}
现在你可以像下那样简单地调用你的方法:
boolean solveable = isSolvable(values);
使用Java 8(及更高版本),您可以使用流简化阵列创建代码:
int[] values = myList.stream().mapToInt(Tile::getValue).toArray();