prologzebra-puzzle

Write a Prolog program to solve this problem


I am new to Prolog kindly assist. Hunter, Laura, Jim, Sally, and Jack work in the same building with five adjacent offices. Hunter doesn’t work in the 5th office and Laura doesn’t work in the first office. Jim doesn’t work in the first or last office, and he is not in an office adjacent to Jack or Laura. Sally works in some office higher than Laura’s. Who works in what offices?

Write a Prolog program to solve this problem. Define what adjacency is, then what the offices are, and then create a layout(X) that allows you to put in all the rules. Each person is put into an office that doesn’t break any of the rules given.


Solution

  • In this answer we use . Read a tutorial on clpfd for details!

    :- use_module(library(clpfd)).
    
    puzzle(P) :-
       puzzle_vars(P, Zs),
       labeling([], Zs).
    
    puzzle_vars(P, Zs) :-
       P  = [hunter-Hunter, jack-Jack, jim-Jim,
             laura-Laura, sally-Sally],
       Zs = [Hunter,Laura,Jim,Sally,Jack],
       Zs ins 1..5,
       all_different(Zs),
       Hunter #\= 5,
       Laura  #\= 1,
       Jim    #\= 1,
       Jim    #\= 5, 
       abs(Jim-Jack)  #\= 1,
       abs(Jim-Laura) #\= 1,
       Sally #> Laura.
    

    Who works in what offices? Let's ask Prolog!

    ?- puzzle(P).
       P = [hunter-3, jack-1, jim-4, laura-2, sally-5]
    ;  false.