gpt4 book ai didi

java - 将 arraylist 发送到数组以检查难题是否可解决

转载 作者:行者123 更新时间:2023-11-30 06:24:29 25 4
gpt4 key购买 nike

我想发送我的数组列表:

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[] stateisSolvable(int[] state) 以便可以检查我的谜题是否可解。

这可能是一些愚蠢的简单的事情,但尝试后我的头很软在本论坛中搜索解决方案。

我的图 block 类:

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 + " ]";
}
}

}

此致。

最佳答案

一般方法是使用循环构建一个 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();

关于java - 将 arraylist 发送到数组以检查难题是否可解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484198/

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