Download presentation

Presentation is loading. Please wait.

Published byMaximo Talton Modified over 2 years ago

1
PROLOG MORE PROBLEMS

2
MAGIC PUZZLE 3 X 3 3 X 3 square Digits 1 to 9 All rows are equal to 15 All columns are equal to 15 Both diagonals are equal to 15

3
MAGIC PUZZLE 3 X 3 3 X 3 square X1X2X3 X4X5X6 X7X8X9

4
MAGIC PUZZLE 3 X 3 Basically only one solution (+symmetries) Check it out: all totals are 15

5
MAGIC PUZZLE 3 X 3 All digits should be different All digits are between 1 and 9 Set of equations: –X1 + X2 + X3 = 15 (1 st row) –X4 + X5 + X6 = 15 (2 nd row) – … –X3 + X5 + X7 = 15 (opposite diagonal)

6
MAGIC PUZZLE 3 X 3 solve(X1,X2,X3,X4,X5,X6,X7,X8,X9) :- member(X1,[1,2,3,4,5,6,7,8,9]),.. alldifferent([X1,X2,X3,….,X6,X7,X8,X9]), X1 + X2 + X3 =:= 15,.. X3 + X5 + X7 =:= 15.

7
MAGIC PUZZLE 3 X 3 Would take about 7 minutes to generate the solution Intuitively –The average number is 5 –There are 3 numbers in each row, column, diagonal –Average number (5) * # numbers/row.. (3) = 15 5 is probably in the middle (it is) hard code 5 in the middle to speed up the code.

8
TOWERS OF HANOI 3 Towers: left, center, right N disks on left tower All disks have a different diameter A smaller disk must be on top of a bigger disk; it can be alone too We want to move the N disks to the center tower

9
TOWERS OF HANOI Starting position with 3 disks

10
TOWERS OF HANOI Solution (general case: N >= 2): To move N disks from A to B using C –Move (N-1) disks from A to C using B (recursive call) –Move 1 disk from A to B –Move (N-1) disks from C to B using A (recursive call) Base Case (only 1 disk to move from A to B; no need for C here): –Move 1 disk from A to B

11
TOWERS OF HANOI Problem: Can we move N disks from tower A to tower B using tower C? Yes or No answer + printing out all the steps Predicate move takes 4 arguments: the number of disks, and 3 towers

12
TOWERS OF HANOI Base case: Move 1 disk from A to B move(1,A,B,_) :- –write(Move top disk from ), –write(A), –write( to ), –write(B), –nl.

13
TOWERS OF HANOI General case: Move N disks from A to B using C move(N,A,B,C) :- –N > 1, –M is N – 1, –move(M,A,C,B), –move(1,A,B,_), –move(M,C,B,A).

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google