jokeSlayer94
jokeSlayer94

Reputation: 143

getting a prolog program to print out results instead of booleans

imagine a 2d map with 6 regions R1-R6. Each region should be colored in with 1 of 4 colors, but no adjacent regions can be the same color.

here is my code:

% #1 initial facts
next(red,green).
next(red,blue).
next(red,yellow).
next(green,red).
next(green,blue).
next(green,yellow).
next(blue,green).
next(blue,yellow).
next(blue,red).
next(yellow,red).
next(yellow,blue).
next(yellow,green).
% #1 actual program
color(R1,R2,R3,R4,R5,R6).
color(R1,R2,R3,R4,R5,R6):-
    % region adjacency relations
    next(R1,R2),
    next(R1,R3),
    next(R1,R4),
    next(R2,R4),
    next(R2,R5),
    next(R3,R4),
    next(R3,R6),
    next(R4,R5),
    next(R4,R6).

Expected output:

R1= red, R2= blue, R3= blue, R4= green, R5= red, R6= red

My Output:

true

what am I doing wrong? Is this even wrong? Even if my code is successfully finding the right color configuration, how do I get it to print out its findings?

Upvotes: 1

Views: 293

Answers (2)

CapelliC
CapelliC

Reputation: 60014

in case your Prolog doesn't offer dif/2, or you are willing to better understand the basic of this language, here is a possible correction of your code:

next(R1,R2) :-
    select(R1, [red, green, blue, yellow], Cs),
    member(R2, Cs).

color(R1,R2,R3,R4,R5,R6):-
    % region adjacency relations
    next(R1,R2),
    next(R1,R3),
    next(R1,R4),
    next(R2,R4),
    next(R2,R5),
    next(R3,R4),
    next(R3,R6),
    next(R4,R5),
    next(R4,R6).

this is marginally more efficient - on the inference count - than using dif/2.

edit still better, using iso_dif/2, or the 'old style' version

next(R1, R2) :- color(R1), color(R2), R1 \= R2.

of course, color/1 comes from mat' answer

Upvotes: 0

mat
mat

Reputation: 40768

Your program is currently too general due to the first clause of color/6. You get the solution you expect (as one among many different solutions) if you simply remove that first clause.

There is also a more beautiful way to write your program:

regions(Rs):-
        Rs = [R1,R2,R3,R4,R5,R6],
        % neighbouring regions have different colors
        dif(R1, R2),
        dif(R1, R3),
        dif(R1, R4),
        dif(R2, R4),
        dif(R2, R5),
        dif(R3, R4),
        dif(R3, R6),
        dif(R4, R5),
        dif(R4, R6),
        maplist(color, Rs).

color(red).
color(green).
color(blue).
color(yellow).

Example query and sample solutions:

?- regions(Rs).
Rs = [red, green, green, blue, red, red] ;
Rs = [red, green, green, blue, red, yellow] ;
Rs = [red, green, green, blue, yellow, red] ;
etc.

Notice the use of dif/2 () to state that two terms are different.

For more serious map coloring tasks, consider using constraints.

Upvotes: 3

Related Questions