1

I am trying to solve the following question:

A puzzle consists of three black pegs, three white pegs, and an empty space in the middle ("BBBOWWW").

The puzzle has two moves with associated costs: (a) A peg may move into an adjacent empty location (cost of 1). (b) A peg can hop over one or two other pegs into the empty position. This has a cost equal to the number of pegs jumped over.

The goal is to have all the white pegs to the left of all the black pegs. The position of the blank is not important.

I am allowed to use any programming language I choose, and am hoping to solve this using Prolog to gain experience. I have been able to implement a simplified version of this problem that finds the shortest path, but am struggling with the A* and heuristic implementation.

I have attached the following Prolog code and the query I am using.

My question is how to go about implementing the A* algorithm into my code? I have not been able to find useful examples and would appreciate any guidance/hints.

Thank you.

QUERY:

length(Path, _),
initial_state(Initial),
phrase(moves(Initial), Path),
maplist(writeln, Path).

PROGRAM:

% Initial state
initial_state([b,b,b,o,w,w,w]).

% 7 possible goal states
goalState([w,w,w,o,b,b,b]).
goalState([w,w,w,b,o,b,b]).
goalState([w,w,w,b,b,b,o]).
goalState([w,w,o,w,b,b,b]).
goalState([w,o,w,w,b,b,b]).
goalState([o,w,w,w,b,b,b]).

% All possible moves
move([E|Es]) --> [E], move(Es).
move([b,o|Solution]) --> [o,b], list(Solution). 
move([o,w|Solution]) --> [w,o], list(Solution).
move([o,X,w|Solution]) --> [w,X,o], list(Solution).
move([b,X,o|Solution]) --> [o,X,b], list(Solution).
move([o,X,X,w|Solution]) --> [w,X,X,o], list(Solution).
move([b,X,X,o|Solution]) --> [o,X,X,b], list(Solution).
move([w,X,X,o|Solution]) --> [o,X,X,w], list(Solution).
move([o,X,X,b|Solution]) --> [b,X,X,o], list(Solution).

list([]) --> [].
list([L|Solution]) --> [L], list(Solution).

moves(S)  --> [S], {goalState(S)}.
moves(S0) --> [S0], {phrase(move(S0),S)}, moves(S).

I based my initial solution off of the following: Prolog program that solves the peg jump puzzle

false
  • 10,264
  • 13
  • 101
  • 209
ABC
  • 11
  • 2
  • 1
    you're missing `goalState([w,w,w,b,b,o,b]).` – CapelliC Oct 11 '18 at 06:46
  • You have a state-space search example with several heuristic search methods at https://github.com/LogtalkDotOrg/logtalk3/tree/master/examples/searching Note that, besides the algorithm implementation itself, you also need to find good heuristics for this particular problem. – Paulo Moura Oct 11 '18 at 08:33
  • Excellent - thank you both! :) – ABC Oct 11 '18 at 23:17
  • Richard O'Keefe [wrote](http://www.cs.otago.ac.nz/cosc348/phylo/astar.pdf) a nice tutorial on implementing A* in Prolog. – emi Jan 14 '20 at 15:14

0 Answers0