4.1 Retrieving structured information from a database

Slides:



Advertisements
Similar presentations
Recognising Languages We will tackle the problem of defining languages by considering how we could recognise them. Problem: Is there a method of recognising.
Advertisements

Recognising Languages We will tackle the problem of defining languages by considering how we could recognise them. Problem: Is there a method of recognising.
4. Using Structures: Example Programs. Contents l Retrieving structured information from a database l Doing data abstraction l Simulating a non-deterministic.
4b Lexical analysis Finite Automata
1. An Overview of Prolog.
8 Queens. Problem: Placing 8 queens on a chessboard such that they don’t attack each other Three different Prolog programs are suggessted as solutions.
PROLOG 8 QUEENS PROBLEM.
1 COMP313A Programming Languages Logic Programming (6)
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
1 1 CDT314 FABER Formal Languages, Automata and Models of Computation Lecture 3 School of Innovation, Design and Engineering Mälardalen University 2012.
Introduction to Graph “theory”
A Third Look At Prolog Chapter Twenty-TwoModern Programming Languages, 2nd ed.1.
Copyright © Cengage Learning. All rights reserved. CHAPTER 1 SPEAKING MATHEMATICALLY SPEAKING MATHEMATICALLY.
1 Introduction to Computability Theory Lecture12: Decidable Languages Prof. Amos Israeli.
1 Introduction to Computability Theory Lecture15: Reductions Prof. Amos Israeli.
1 Introduction to Computability Theory Lecture12: Reductions Prof. Amos Israeli.
Introduction to Computability Theory
61 Nondeterminism and Nodeterministic Automata. 62 The computational machine models that we learned in the class are deterministic in the sense that the.
CHAPTER 4 Decidability Contents Decidable Languages
Fall 2004COMP 3351 A Universal Turing Machine. Fall 2004COMP 3352 Turing Machines are “hardwired” they execute only one program A limitation of Turing.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Using Structures: Example Programs Notes for Ch.4 of Bratko For CSCE 580 Sp03.
FSA Lecture 1 Finite State Machines. Creating a Automaton  Given a language L over an alphabet , design a deterministic finite automaton (DFA) M such.
CS5371 Theory of Computation Lecture 8: Automata Theory VI (PDA, PDA = CFG)
Copyright © Cengage Learning. All rights reserved.
1 Introduction to Computability Theory Lecture11: The Halting Problem Prof. Amos Israeli.
Relations Chapter 9.
Chapter 9 1. Chapter Summary Relations and Their Properties n-ary Relations and Their Applications (not currently included in overheads) Representing.
Set theory Sets: Powerful tool in computer science to solve real world problems. A set is a collection of distinct objects called elements. Traditionally,
Section 11.4 Language Classes Based On Randomization
Data Structures Using C++ 2E Chapter 6 Recursion.
FATIH UNIVERSITY Department of Computer Engineering Programming Style and Technique Notes for Ch.8 of Bratko For CENG421&553 Fall03.
Data Structures Using C++ 2E Chapter 6 Recursion.
FATIH UNIVERSITY Department of Computer Engineering Using Structures: Example Programs Notes for Ch.4 of Bratko For CENG 421 Fall03 Zeynep Orhan.
Lecture 03: Theory of Automata:08 Finite Automata.
DECIDABILITY OF PRESBURGER ARITHMETIC USING FINITE AUTOMATA Presented by : Shubha Jain Reference : Paper by Alexandre Boudet and Hubert Comon.
April 10, 2002Applied Discrete Mathematics Week 10: Relations 1 Counting Relations Example: How many different reflexive relations can be defined on a.
Chapter 9. Chapter Summary Relations and Their Properties Representing Relations Equivalence Relations Partial Orderings.
Chapter 9. Chapter Summary Relations and Their Properties n-ary Relations and Their Applications (not currently included in overheads) Representing Relations.
An ordered n-tuple is a set of n objects with an order associated with them. If n objects are represented by x 1, x 2,..., x n, then we write the ordered.
Lecture 07: Formal Methods in SE Finite Automata Lecture # 07 Qaisar Javaid Assistant Professor.
Constraint Satisfaction Problems (CSPs) CPSC 322 – CSP 1 Poole & Mackworth textbook: Sections § Lecturer: Alan Mackworth September 28, 2012.
Set, Combinatorics, Probability & Number Theory Mathematical Structures for Computer Science Chapter 3 Copyright © 2006 W.H. Freeman & Co.MSCS Slides Set,
Introduction to Graph “theory” Why do we care about graph theory in testing and quality analysis? –The “flow” (both control and data) of a design, within.
Chapter 9. Section 9.1 Binary Relations Definition: A binary relation R from a set A to a set B is a subset R ⊆ A × B. Example: Let A = { 0, 1,2 } and.
1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14.
Discrete Structures1 You Never Escape Your… Relations.
1 CD5560 FABER Formal Languages, Automata and Models of Computation Lecture 3 Mälardalen University 2010.
Quadrant II Quadrant I (, ) __-axis Origin (, ) Quadrant IVQuadrant III __-axis x-intercept of l 1 is (, ) To find the x-intercept, set__ =0 and solve.
1. Interpret graphs. 2. Write a solution as an ordered pair. 3. Decide whether a given ordered pair is a solution of a given equation. 4. Complete ordered.
Lecture # 12. Nondeterministic Finite Automaton (NFA) Definition: An NFA is a TG with a unique start state and a property of having single letter as label.
1 Linear Bounded Automata LBAs. 2 Linear Bounded Automata (LBAs) are the same as Turing Machines with one difference: The input string tape space is the.
1 Turing’s Thesis. 2 Turing’s thesis: Any computation carried out by mechanical means can be performed by a Turing Machine (1930)
Chapter 9. Chapter Summary Relations and Their Properties n-ary Relations and Their Applications (not currently included in overheads) Representing Relations.
CS 203: Introduction to Formal Languages and Automata
Recognising Languages We will tackle the problem of defining languages by considering how we could recognise them. Problem: Is there a method of recognising.
A relation is a correspondence between two sets. If x and y are two elements in these sets and if a relation exists between x and y, then x corresponds.
R. Johnsonbaugh Discrete Mathematics 5 th edition, 2001 Chapter 10 Automata, Grammars and Languages.
Chapter 8 Properties of Context-free Languages These class notes are based on material from our textbook, An Introduction to Formal Languages and Automata,
Lecture 04: Theory of Automata:08 Transition Graphs.
Chapter 13 Backtracking Introduction The 3-coloring problem
November 12, 2009Theory of Computation Lecture 17: Calculations on Strings II 1 Numerical Representation of Strings First, we define two primitive recursive.
A relation is a correspondence between two sets. If x and y are two elements in these sets and if a relation exists between x and y, then x corresponds.
The Acceptance Problem for TMs
Transition Graphs.
Relations Chapter 9.
Lexical analysis Finite Automata
PROPERTIES OF REGULAR LANGUAGES
Introduction to Finite Automata
Chapter Five: Nondeterministic Finite Automata
Presentation transcript:

Part 1 The Prolog Language Chapter 4 Using structures: Example Programs

4.1 Retrieving structured information from a database The family structure: Each family has three components: husband, wife, and children. The children are represented by a list. Each person represented by a structure of four components: name, surname(姓), date of birth, and job. The job information is ‘unemployed’, or it specifies the working organization and salary.

4.1 Retrieving structured information from a database family . person date fox tom works 1960 may 7 15200 bbc ann unemployed 1961 9 pat 1983 5 jim []

4.1 Retrieving structured information from a database The family can be stored in the database by the clause: family( person( tom, fox, date(7,may,1960), works( bbc, 15200)), person( ann, fox, date(9,may,1961), unemployed), [ person( pat, fox, date(5,may,1983), unemployed), person( jim, fox, date(5,may,1983), unemployed) ] ). How to retrieval the information from the database? |?- family( person( Y, armstrong, _, _), _, _). Find all fathers of Armstrong families. |?- family(person( _, X, _, _), _, [ _, _, _] ). Find all families with three children. |?- family( _, person(Name, Surname, _, _), [ _, _, _ |_] ). Find all married women that have at least three children.

4.1 Retrieving structured information from a database These procedures can serve as a utility to make the interaction with the database more comfortable. husband( X) :- family( X, _, _). wife( X) :- family( _, X, _). child( X) :- family( _, _, Children), member( X, Children). exists( Persons) :- husband( Persons); wife( Persons); child( Persons). dateofbirth( person(_, _, Date, _), Date). salary( person(_, _, _, works(_, S)), S). salary( person(_, _, _, unemployed), 0). We can use these utilities, for example, in the following queries to the database: Find the names of all the people in the database: |?- exists( person( Name, Surname, _, _)).

4.1 Retrieving structured information from a database We can use these utilities, for example, in the following queries to the database (con.): Find all children born in 2000: |?- child( X), dateofbirth( X, date( _, _, 2000)). Find all employed wives: |?- wife( person( Name, Surname, _, works(_, _))). Find the names of unemployed people who were born before 1973: |?- exists( person( Name, Surname, date(_, _, Year), unemployed)), Year < 1973. Find people born before 1960 whose salary is less than 8000: |?- exists( Person), dateofbirth( Person, date(_, _, Year)), Year < 1960, salary( Person, Salary), Salary < 8000. Find the names of families with at least three children: |?- family( person( _, Name, _, _), _, [_, _, _| _]).

Exercise Write queries to find the following from the family database: Names of families without children; All employed children; Names of families with employed wives and unemployed husbands; All the children whose parents differ in age by at least 15 years.

4.1 Retrieving structured information from a database To calculate the total income of family it is useful to define the sum of salaries of a list of people as a two-argument relation: total( List_of_people, Sum_of_their_salaries). This relation can be programmed as: total( [], 0). total( [Person |List], Sum) :- salary( Person, S), total( List, Rest), Sum is S + Rest. The total income of families can then be found: |?- family( Husband, Wife, Children), total( [Husband, Wife | Children], Income).

4.1 Retrieving structured information from a database Let the length relation count the number of elements of a list, as defined in Section 3.4. Then we can specify all families that have an income per family member of less then 2000: |?- family( Husband, Wife, Children), total( [Husband, Wife | Children], Income), length( [Husband, Wife | Children], N), Income/N < 2000.

Exercises If we write a query to find people born before 1960 whose salary is less than 8000 as follows. Is it a correct query? If not, please correct this query. | ?- dateofbirth( Person, date(_, _, Year)), Year < 1960, salary( Person, Salary), Salary < 8000. Define the relation twins(Child1, Child2) to find twins in the family database.

4.2 Doing data abstraction Data abstraction (資料抽象化) can make the use of information possible without the programmer having to think about the details of how the information is actually represented. In the previous section, each family was represented by a Prolog clause: family( person( tom, fox, date(7,may,1960), works( bbc, 15200)), person( ann, fox, date(9,may,1961), unemployed), [ person( pat, fox, date(5,may,1983), unemployed), person( jim, fox, date(5,may,1983), unemployed) ] ). Here, a family will be represented as a structured object, for example: FoxFamily = family( person( tom, fox, _, _), _, _)

4.2 Doing data abstraction Let us define some relations through which the user can access particular components of a family without knowing the details of Figure 4.1: selector_relation( Object, Component_selected) Here are some selectors for the family structure: husband( family( Husband, _, _), Husband). wife( family( _, Wife, _), Wife). children( family( _, _, ChildList), ChildList). Thus, we can also define selectors for particular children: firstchild( Family, First):- children( Family, [First | _]).

4.2 Doing data abstraction More selectors for particular children: firstchild( Family, First):- children( Family, [First | _]). secondchild( Family, Second):- children( Family, [_, Second | _]). … nthchild( N, Family, Child) :- children( Family, ChildList), nth_member( N, ChildList, Child). Some related selectors of persons: firstname( person( Name, _, _, _), Name). surname( person( _, Surname, _, _), Surname). born( person( _, _, Date, _), Date).

4.2 Doing data abstraction How can we benefit from selector relations? We can forget about the particular way that structured information is represented. For example, the user does not have to know that the children are represented as a list. Assume that we want to say that Tom Fox and Jim Fox belong to the same family and that Jim is the second child of Tom. Using the selector relations above, we can define two persons, call them Person1 and Person2, and the family. firstname( Person1, tom), surname(Person1, fox), firstname( Person2, jim), surname(Person2, fox), husband( Family, Person1), secondchild( Family, Person2)

4.2 Doing data abstraction As a result, the variables Person1, Person2, and Family are instantiated as: Person1 = person( tom, fox, _, _) Person2 = person( jim, fox, _, _) Family = family( person( fom, fox, _, _), _, [_, person( jim, fox)|_]) The use of selector relations also make programs easier to modify.

Exercise Complete the definition of nthchild by defining the relation nth_member(N, List, X) which is true if X is the Nth member of List. nthchild( N, Family, Child) :- children( Family, ChildList), nth_member( N, ChildList, Child).

4.3 Simulating a non-deterministic automaton A non-deterministic finite automaton is an abstract machine that reads as input a string of symbols and decides whether to accept or to reject the input string. An automaton has a number of states and it is always in one of the states. It can change its state by moving from the current state to another state. For example: States: {s1, s2, s3, s4}. Initial state: s1. Final state: s3. Symbols: {a, b}. null (null symbol) There arcs labeled null correspond to silent moves of the automaton. The move occurs without any reading of input. s1 s2 s4 s3 a b null

4.3 Simulating a non-deterministic automaton The automaton is said to accept the input string if there is a transition path in the graph such that (1) It starts with the initial state, (2) It ends with a final state, and (3) The arc labels along the path correspond to the complete input string. For example: The automaton will accept the strings ab and aabaab. It will reject the strings abb and abba. In fact, this automaton accepts any string that terminates with ab, and rejects all others. s1 s2 s4 s3 a b null

4.3 Simulating a non-deterministic automaton In Prolog, an automaton can be specified by three relations: (1) A unary relation final defines the final states of the automaton. final(F) means F is a final state. (2) A three-argument relation trans which defines the state transitions so that trans( S1, X, S2) means that a transition from a state S1 to S2 is possible when the current input symbol X is read. (3) A binary relation silent( S1, S2) meanings that a silent move is possible from S1 to S2. s1 s2 s4 s3 a b null

4.3 Simulating a non-deterministic automaton For example: final(s3). trans(s1, a, s1). trans(s1, a, s2). trans(s1, b, s1). trans(s2, b, s3). trans(s3, b, s4). silent(s2, s4). silent(s3, s1). s1 s2 s4 s3 a b null

4.3 Simulating a non-deterministic automaton Represent input strings as Prolog list. For example, [a, a, a, b]. Define the acceptance of a string from a given state: accepts( State, String) The binary relation accepts is true if the automaton, starting from the state State as initial state, accepts the string String. For example: | ?- accepts( s1, [a, a, a, b]). true ? yes s1 s2 s4 s3 a b null

4.3 Simulating a non-deterministic automaton The accepts relation can be define by three clauses: (1) The empty string, [], is accepted from a state State if State is a final state. accepts( State, []):- final( State). (2) A non-empty string is accepted from State if reading the first symbol in the string can bring the automaton into some state State1, and the rest of the string is accepted from State1. accepts( State, [ X| Rest]):- trans( State, X, State1), accepts( State1, Rest). (3) A string is accepted from State if the automaton can make a silent move from State to State1 and then accept the (whole) input string from State1. accepts( State, String):- silent( State, State1), accepts( State1, String). S S1 X S S1 null

4.3 Simulating a non-deterministic automaton For example: | ?- accepts( s1, [a, a, a, b]). true ? yes | ?- accepts( S, [a, b]). S = s1 ? ; S = s3 ? ; no | ?- accepts( s1, [X1, X2, X3]). X1 = a X2 = a X3 = b ? ; X1 = b s1 s2 s4 s3 a b null | ?- String=[_,_,_,_], accepts( s1, String). String = [a,a,a,b] ? ; String = [a,b,a,b] ? ; String = [b,a,a,b] ? ; String = [b,b,a,b] ? ; no

Exercise What kind of strings can be accepted by this automaton? Please write a Prolog program and test it. s1 s2 s4 s3 a b null s5 s6 s7 c

4.5 The eight queens problem The problem here is to place eight queens on the empty chessboard in such a way that no queen attacks any other queen. The solution will be programmed as a unary predicate Solution( Pos) which is true if and only if Pos represents a position with eight queens that do not attack each other. In this section, we will present three programs based on somewhat different representations on the problem.

4.5.1 The eight queens problem— Program 1 Figure 4.6 shows one solution of the eight queens problem. And the list representation of solution is: [1/4, 2/2, 3/7, 4/3, 5/6, 6/8, 7/5, 8/1] In the program, we choose the representation of the board position: [X1/Y1, X2/Y2, …, X8/Y8] We also can fix the X-coordinates so that the solution list will fit the following template: [1/Y1, 2/Y2, …, 8/Y8] 8 ● 7 6 5 4 3 2 1

4.5.1 The eight queens problem— Program 1 The solution relation can be formulated by considering two cases: Case 1: The list of queens is empty. The empty list is certainly a solution because there is no attack. Case 2: The list of queens is non-empty. Then it looks like this: [X/Y| Others] (1) There must be no attack between the queens in the list Others; that is, Others itself must also be a solution. (2) X and Y must be integers between 1 and 8. (3) A queen at square X/Y must not attack(攻擊) any of the queens in the list Others. solution([X/Y|Others]) :- solution( Others), member( Y, [1,2,3,4,5,6,7,8]), noattack( X/Y, Others).

4.5.1 The eight queens problem— Program 1 Now define the noattack relation: noattack( Q, Qlist) Case 1: If the list Qlist is empty then the relation is certainly true because there is no queen to be attacked. noattack( _, [] ). Case 2: If Qlist is not empty then it has the form [Q1|Qlist1] and two conditions must be satisfied: (1) the queen at Q must not attack the queen at Q1, and (2) the queen at Q must not attack any of the queens in Qlist1. To specify that a queen at some square does not attack another square is easy: the two squares must not be in the same row, the same column or the same diagonal.

4.5.1 The eight queens problem— Program 1 Since the two squares must not be in the same row, the same column or the same diagonal, so The Y-coordinates of the queens are different, and They are not in the same diagonal, either upward or downward; that is, the distance between the squares in the X-direction must not be equal to that in the Y-direction. noattack( _, [] ). % Nothing to attack noattack( X/Y, [X1/Y1 | Others] ) :- Y =\= Y1, % Different Y-coordinates Y1-Y =\= X1-X, % Different diagonals Y1-Y =\= X-X1, noattack( X/Y, Others).

4.5.1 The eight queens problem— Program 1 % Figure 4.7 Program 1 for the eight queens problem. solution( [] ). solution( [X/Y | Others] ) :- solution( Others), member( Y, [1,2,3,4,5,6,7,8] ), noattack( X/Y, Others). noattack( _, [] ). noattack( X/Y, [X1/Y1 | Others] ) :- Y =\= Y1, Y1-Y =\= X1-X, Y1-Y =\= X-X1, member( Item, [Item | Rest] ). member( Item, [First | Rest] ) :- member( Item, Rest). % A solution template template( [1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8] ).

4.5.1 The eight queens problem— Program 1 | ?- template( S), solution( S). S = [1/4, 2/2, 3/7, 4/3, 5/6, 6/8, 7/5, 8/1] ? ; S = [1/5, 2/2, 3/4, 4/7, 5/3, 6/8, 7/6, 8/1] ? ; S = [1/3, 2/5, 3/2, 4/8, 5/6, 6/4, 7/7, 8/1] ? ; S = [1/3, 2/6, 3/4, 4/2, 5/8, 6/5, 7/7, 8/1] ? ; S = [1/5, 2/7, 3/1, 4/3, 5/8, 6/6, 7/4, 8/2] ? ; S = [1/4, 2/6, 3/8, 4/3, 5/1, 6/7, 7/5, 8/2] ? ; S = [1/3, 2/6, 3/8, 4/1, 5/4, 6/7, 7/5, 8/2] ? ; S = [1/5, 2/3, 3/8, 4/4, 5/7, 6/1, 7/6, 8/2] ? ; S = [1/5, 2/7, 3/4, 4/1, 5/3, 6/8, 7/6, 8/2] ? ; S = [1/4, 2/1, 3/5, 4/8, 5/6, 6/3, 7/7, 8/2] ? ; S = [1/3, 2/6, 3/4, 4/1, 5/8, 6/5, 7/7, 8/2] ? ; S = [1/4, 2/7, 3/5, 4/3, 5/1, 6/6, 7/8, 8/2] ? ; S = [1/6, 2/4, 3/2, 4/8, 5/5, 6/7, 7/1, 8/3] ? ; S = [1/6, 2/4, 3/7, 4/1, 5/8, 6/2, 7/5, 8/3] ? ; S = [1/1, 2/7, 3/4, 4/6, 5/8, 6/2, 7/5, 8/3] ? …

4.5.1 The eight queens problem— Program 1 | ?- solution([1/3,2/5,3/2,4/8,5/6,6/4,7/7,8/1]). true ? yes | ?- solution([1/3,2/5,3/2,4/8,5/6,6/4,7/7,8/8]). no | ?- solution([7/3,7/5,7/2,7/8,7/6,7/4,7/7,7/1]). Why?

4.5.2 The eight queens problem— Program 2 In the program, we choose the representation of the board position: [Y1, Y2, …, Y8] No information is lost if the X-coordinates were omitted. Each solution is therefore represented by a permutation of the list [1, 2, 3, 4, 5, 6, 7, 8] Such a permutation, S, is a solution if all the queens are safe. solution( S):- permutation([1,2,3,4,5,6,7,8], S), safe( S).

4.5.2 The eight queens problem— Program 2 Define the safe relation: (1) S is the empty list. This is certainly safe as there is nothing to be attacked. safe( [] ). (2) S is a non-empty list of the form [Queen|Others]. This is safe if the list Others is safe, and Queen does not attack any queen in the list Others. safe( [Queen | Others] ) :- safe( Others), noattack( Queen, Others).

4.5.2 The eight queens problem— Program 2 The goal noattack( Queen, Others) is meant to ensure that Queen does not attack Others when the X-distance between Queen and Others is equal to 1. We add this distance as the third argument of the noattack relation. noattack( Queen, Others, Xdist) noattack( _, [], _). noattack( Y, [Y1 | Ylist], Xdist) :- Y1-Y =\= Xdist, Y-Y1 =\= Xdist, Dist1 is Xdist + 1, noattack( Y, Ylist, Dist1).

4.5.2 The eight queens problem— Program 2 The noattack goal in the safe relation has to be modified to noattack( Queen, Others, 1) ● ● Others Queen X-dist =1 Others Queen X-dist =3

4.5.2 The eight queens problem— Program 2 % Figure 4.9 Program 2 for the eight queens problem. solution( Queens) :- permutation( [1,2,3,4,5,6,7,8], Queens), safe( Queens). permutation( [], [] ). permutation( [Head | Tail], PermList) :- permutation( Tail, PermTail), del( Head, PermList, PermTail). del( Item, [Item | List], List). del( Item, [First | List], [First | List1] ) :- del( Item, List, List1). safe( [] ). safe( [Queen | Others] ) :- safe( Others), noattack( Queen, Others, 1). noattack( _, [], _). noattack( Y, [Y1 | Ylist], Xdist) :- Y1-Y =\= Xdist, Y-Y1 =\= Xdist, Dist1 is Xdist + 1, noattack( Y, Ylist, Dist1).

4.5.2 The eight queens problem— Program 2 | ?- solution( S). S = [5,2,6,1,7,4,8,3] ? ; S = [6,3,5,7,1,4,2,8] ? ; S = [6,4,7,1,3,5,2,8] ? ; S = [3,6,2,7,5,1,8,4] ? ; S = [6,3,1,7,5,8,2,4] ? ; S = [6,2,7,1,3,5,8,4] ? ; S = [6,4,7,1,8,2,5,3] ? ; S = [3,6,2,7,1,4,8,5] ? ; S = [6,3,7,2,4,8,1,5] ? ; S = [6,3,7,4,1,8,2,5] ? ; S = [2,6,1,7,4,8,3,5] ? ; S = [6,2,7,1,4,8,5,3] ? ; S = [6,3,7,2,8,5,1,4] ? ; S = [5,7,2,6,3,1,4,8] ? ;…

4.5.2 The eight queens problem— Program 2 | ?- solution([5,2,6,1,7,4,8,3]). true ? yes | ?- solution([5,2,6,1,7,4,8,X]). X = 3 ? | ?- solution([5,2,6,1,7,Z,Y,X]). X = 3 Y = 8 Z = 4 ? ; no | ?- solution([5,2,6,1,7,7,Y,X]).

4.5.3 The eight queens problem— Program 3 The reasoning for the eight queens problem: Each queen has to be placed on some square; that is, into some column, some row, some upward diagonal and some downward diagonal. To make sure that all the queens are safe, each queen must be placed in a different column, a different row, a different upward and a different downward diagonal. Thus, define x columns y rows u upward diagonals (u = x - y) v downward diagonals (v = x + y)

4.5.3 The eight queens problem— Program 3 -7 -2 +7 u=x-y y The domains for all four dimensions are: Dx=[1,2,3,4,5,6,7,8] Dy=[1,2,3,4,5,6,7,8] Du=[-7,-6,-5,-4,-3,-2, -1,0,1,2,3,4,5,6,7] Dv=[2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16] 8 7 6 5 4 ● 3 2 1 x v=x+y 2 6 16

4.5.3 The eight queens problem— Program 3 The eight queens problem can be stated as follows: Select eight 4-tuples (X, Y, U, V) from the domains (X from Dx, Y from Dy, etc.), never using the same element twice from any of the domains. Of course, once X and Y are chosen, U and V are determined. The solution can then be as follows: given all four domains, select the position of the first queen, delete the corresponding items from the four domains, and then use the rest of the domains for placing the rest of the queens.

4.5.3 The eight queens problem— Program 3 % Figure 4.11 Program 3 for the eight queens problem. solution( Ylist) :- sol( Ylist, [1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8], [-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7], [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] ). sol( [], [], Dy, Du, Dv). sol( [Y | Ylist], [X | Dx1], Dy, Du, Dv) :- del( Y, Dy, Dy1), U is X-Y, del( U, Du, Du1), V is X+Y, del( V, Dv, Dv1), sol( Ylist, Dx1, Dy1, Du1, Dv1). del( Item, [Item | List], List). del( Item, [First | List], [First | List1] ) :- del( Item, List, List1). The domains for all four dimensions are: Dx=[1,2,3,4,5,6,7,8] Dy=[1,2,3,4,5,6,7,8] Du=[-7,-6,-5,-4,-3,-2, -1,0,1,2,3,4,5,6,7] Dv=[2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16]

4.5.3 The eight queens problem— Program 3 | ?- solution( Ylist). Ylist = [1,5,8,6,3,7,2,4] ? ; Ylist = [1,6,8,3,7,4,2,5] ? ; Ylist = [1,7,4,6,8,2,5,3] ? ; Ylist = [1,7,5,8,2,4,6,3] ? ; Ylist = [2,4,6,8,3,1,7,5] ? ; Ylist = [2,5,7,1,3,8,6,4] ? ; Ylist = [2,5,7,4,1,8,6,3] ? ; Ylist = [2,6,1,7,4,8,3,5] ? ; Ylist = [2,6,8,3,1,4,7,5] ? ; Ylist = [2,7,3,6,8,5,1,4] ? ; Ylist = [2,7,5,8,1,4,6,3] ? ; Ylist = [2,8,6,1,3,5,7,4] ? ; Ylist = [3,1,7,5,8,2,4,6] ? ; Ylist = [3,5,2,8,1,7,4,6] ? ; Ylist = [3,5,2,8,6,4,7,1] ? ...

4.5.3 The eight queens problem— Program 3 To generation of the domains: gen( N1, N2, List) which will, for two given integers N1 and N2, produce the list List = [ N1, N1+1, N1+2, ..., N2-1, N2] Such procedure is: gen( N, N, [N]). gen( N1, N2, [N1|List]) :- N1 < N2, M is N1+1, gen(M, N2, List). | ?- gen(3,8,L). L = [3,4,5,6,7,8] ? yes

4.5.3 The eight queens problem— Program 3 The gereralized solution relation is: solution( N, S) :- gen(1, N, Dxy), Nu1 is 1-N, Nu2 is N-1, gen(Nu1, Nu2, Du), Nv2 is N+N, gen(2, Nv2, Dv), sol( S, Dxy, Dxy, Du, Dv). For example, a solution to the 12-queens probelm would be generated by: ?- solution( 12, S). S=[1,3,5,8,10,12,6,11,2,7,9,4]

Exercise (1) Please redefine the generation procedure: gen( N1, N2, Step, List) which will, for two given integers N1 and N2 (where N2 should be equal to N1+N*Step), produce the list List = [ N1, N1+Step, N1+2*Step, ..., N3] where N3 is the closest integer smaller than N2.

Exercise (2) Let the squares of the chessboard be represented by pairs of their coordinates of the form X/Y, where both X and Y are between 1 and 8. (a) Define the relation jump(Square1,Square2) according to the knight’s jump on the chessboard. Assume that Square1 is always instantiated to a square while Square2 can be uninstantiated. ?- jump( 1/1, S). S = 3/2; S = 2/3; no (b) Define the relation knightpath(Path) where Path is a list of squares that represent a legal path of a knight (騎士) on an empty chessboard. (c) Using knightpath, write a question to find any knight’s path of length 4 moves from square 2/1 to the opposite edge of the board (Y= 8) that goes through square 5/4 after the second move. For example: path = 2/1 -> 3/3 -> 5/4 -> 6/6 -> 7/8

補充資料 騎士(Knight)的走法與吃法: 1.往某個方向直走兩格之後,再往旁邊走一格。