我刚刚在Java中实现了A *算法,有时它解决了我的滑块拼图,其步骤多于最初的混乱,有时它甚至会进入无限循环。我注意到,当我增加改组因素时,它通常会进入无限循环。 8-puzzle并没有提出这个问题,但从4x3或15-puzzle开始,几乎1/3的生成游戏失败了。
为了清楚起见,我使用了一个shuffling函数来保证生成的游戏可以解决,并且还可以删除" back"每次应用改组运动时都会移动以获得更好的随机化(尽管有时候它仍会产生完整的圆圈)。
使用的启发式函数是曼哈顿距离。
似乎我搞砸了某个地方。谁能帮助我理解为什么会这样?州:
Dictionary<char, double> pizzaPrices = new Dictionary<char, double>(){
{ 'S', 6.99},{ 'M', 8.99},{ 'L', 12.50},{ 'X', 15.00}};
int NumOfPizzas = 0;
double Discount = 0.0, TotalPizzaPrice = 0.0;
char PizzaSizeChar;
Console.Write("What pizza size do you want? ");
PizzaSizeChar = Console.ReadKey().KeyChar; // Gives you the input character
if (pizzaPrices.ContainsKey(PizzaSizeChar))
{
Console.Write("How many pizzas do you want");
NumOfPizzas = int.Parse(Console.ReadLine());
// pizzaPrices[PizzaSizeChar] gives you the price of that char
TotalPizzaPrice = pizzaPrices[PizzaSizeChar] * NumOfPizzas;
Console.WriteLine("Your {0} pizza would normally be {1}", PizzaSizeChar, pizzaPrices[PizzaSizeChar].ToString("C"));
Console.WriteLine("Your total would {0}", TotalPizzaPrice.ToString("C"));
}
else
{
Console.WriteLine("Invalid choice");
}
游戏:
@EqualsAndHashCode(of="board")
public class State{
@Getter @Setter private int[] board;
@Getter @Setter private int g;
@Getter @Setter private int h;
@Getter @Setter private State parent;
public State(int[] board){
this.board = board;
}
public int getF(){
return this.g + this.h;
}
}
ASTAR:
public abstract class Game{
@Getter @Setter private int dimX;
@Getter @Setter private int dimY;
@Getter @Setter private int[] goalBoard;
@Getter @Setter private int swaps;
public int[] generateRandomGame(){
int[] board = Utils.cloneBoard(goalBoard);
List<Integer> possibleMoves;
Integer nextMove = null;
for(int i=0; i<swaps; i++){
possibleMoves = Utils.getPossibleMoves(board, dimX, dimY);
if(nextMove != null){
switch(EnumMoveDirection.getById(nextMove.intValue())){
case UP:
possibleMoves.remove(EnumMoveDirection.DOWN.getIntegerId());
break;
case RIGHT:
possibleMoves.remove(EnumMoveDirection.LEFT.getIntegerId());
break;
case DOWN:
possibleMoves.remove(EnumMoveDirection.UP.getIntegerId());
break;
case LEFT:
possibleMoves.remove(EnumMoveDirection.RIGHT.getIntegerId());
break;
}
possibleMoves.remove(nextMove);
}
nextMove = possibleMoves.get(new Random().nextInt(possibleMoves.size()));
int startIndex = Utils.getStartPositionIndex(board);
int tmp;
switch(EnumMoveDirection.getById(nextMove.intValue())){
case UP:
tmp = board[startIndex];
board[startIndex] = board[startIndex-dimX];
board[startIndex-dimX] = tmp;
break;
case RIGHT:
tmp = board[startIndex];
board[startIndex] = board[startIndex+1];
board[startIndex+1] = tmp;
break;
case DOWN:
tmp = board[startIndex];
board[startIndex] = board[startIndex+dimX];
board[startIndex+dimX] = tmp;
break;
case LEFT:
tmp = board[startIndex];
board[startIndex] = board[startIndex-1];
board[startIndex-1] = tmp;
break;
}
}
return board;
}
}