user766650
user766650

Reputation:

Towers of Hanoi in Prolog

I'm trying to figure out this problem for a CS homework assignment (I'll tag it as homework, I just need a step in the right direction). EDIT: Apparently the 'homework' tag is obsolete and is no longer being used. Anyway, I have to write a rule definition in Prolog that determines of the given list of moves can solve the Tower. I know the instructions are bad, my professor is very unclear, but all I have is that the below conditions must be met:

?- hanoi(1,l,c,r,[[l,r]]).
true.

?- hanoi(1,l,c,r,[[c,r]]).
false.

?- hanoi(2,l,c,r,[[l,c],[l,r],[c,r]]).
true.

?- hanoi(3,l,c,r,M).
M = [[l,r], [l,c], [r,c], [l,r], [c,l], [c,r], [l,r]].

I haven't the slightest clue what any of the above is supposed to hint at me to do, so any guidance will be greatly appreciated! It won't let me tag it as such but, like I said, this is a homework problem (albeit a seemingly ridiculously difficult one, considering the lack of explanation), so I don't necessarily want an answer as much as I want to understand exactly what is going on.

Thank you all very much!!

Upvotes: 1

Views: 1422

Answers (1)

NotAUser
NotAUser

Reputation: 1456

Assuming you know what the problem is about, here's what that representation means:

hanoi(1,l,c,r,[[l,r]]).

This plainly means that there's one element on the left tower in the initial state. l, c and r are the names of the tower. The last argument is the solution. The solution is a list of moves. Each move is a pair [where you get the element from, where you put it]. So in the previous atom, the solution codified is: move the element on the left tower to the right tower.

hanoi(1,l,c,r,[[c,r]]).

This fails because the solution is wrong. The initial state has only elements on the left tower so you can't move it from the central tower if it's not there.

hanoi(2,l,c,r,[[l,c],[l,r],[c,r]]).

This is solved in three moves: left to centre, left to right, centre to right. Same thing for the last query.

Upvotes: 1

Related Questions