Unique Items in a List (Prolog)

I use variation in Einstein Riddle and I am having problems.

When trying to calculate the solution, I will try the following:

solve(Street) :- Street = [_House1,_House2,_House3,_House4,_House5], %hint one goes here %hint two goes here %etc. 

Then I can set the solution by typing: solve (Street)

However, this appears as a solution:

  • house (flower, food, pet, sport)
  • house (flower, food, pet, sport)
  • house ( x , food, pet, sport)
  • house (flower, food, pet, sport)
  • house ( x , flower, pet, sport)

As you can see there 2 times x , the rest are all kinds of products, flowers, pets and sports. But each type is unique: if one person likes flower X, no one else can like X.

Now, why my solution gives 2 x is easy to see: we are given the number of hints, but only 4 colors are mentioned in all the hints. Therefore, Prolog does not know that there is another flower, and simply uses x twice, simply because it is possible and follows all the other prompts.

I want to say that all types of products and colors, etc. on the street are unique, so it should leave a space when it has already used all types. 3 will look like this: house(x , food, pet ,sport) and 5 will look like this: house(_, flower, pet, sport) .

I also tried adding this to the prompts: (say, β€œcactus” is one of the colors not mentioned in the prompts) member(house(cactus,_,_,_), Street)

However, then my program does not end ...

A hint might look like this: is_neighbour(house(_,_,_,football),house(_,_,fish,_), Street), with: is_neighbour(A,B,List) giving true when A and B are next to each other in List . The hint can be translated into: a person who loves football lives next to a person who has fish.

If you need more information, I am ready to develop. :)

+4
source share
1 answer

To express that a flower is not reported twice, and also that all flowers are connected, you can use the permutation predicate / 2: the list of all colors must be a permutation of the list of specified colors. It will look like [untested]

 flowers([], []). flowers([house(Flower,_,_,_)|Street], [Flower|Rest]) :- flowers(Street, Rest). -- ... flowers(Street, Flowers), permutation(Flowers, [kaktus, tulpe, nelke, rose, fingerhut]), 

Edit : For 10 colors, using permutations is probably too slow. Alternative approach

 flower(kaktus). flower(tulpe). flower(nelke). --... flowers(Street,[F1,F2,F3,F4,F5,F6,F7,F8,F9,F10]), flower(F1), flower(F2), F1\=F2, flower(F3), F3\=F1, F3\=F2, flower(F4), F4\=F1, F4\=F2, F4\=F3, --... 
+2
source

All Articles