Vous êtes sur la page 1sur 18

HOME WORK: 1

School: Lovely Honors School Of Technology Department: Computer


Applications
Name of the faculty member: Avneet Kaur Dhawan Course No: CAP 451
Course Title: AI and Logic Programming
Class: MCA(H)-M.Tech(CSE) Term: 4th Section: A3902
Batch:2009
Max. Marks: 5 Date of Allotment: 15-01-2011 Date of Submission:21-01-
2011

Part-A
Q1 The Turing test has often been incorrectly interpreted as being a
test of whether or not a person could distinguish between
responses from a computer and responses from a person. How does
this differ from real Turing test? Are the two tests equivalent? If
not, give reason why they are not?
Sol.

Ans. The Turing test is a test of a machine's ability to demonstrate intelligence. A


human judge engages in a natural language conversation with one human and one
machine, each of which tries to appear human. All participants are separated from one
another. If the judge cannot reliably tell which a machine is, the machine is said to have
passed the test.

The two tests are not equivalent as real turing test is to test the machines intelligence.
But in second case human’s ability is examined whether he/she is able to distinguish
between machine and human communicating with him/her.

Example of turning test:


Q2 Given a 5-litre jug filled with water and an empty 2-litre jug, how
can one obtain precisely 1-litre in the 2-litre jug? Water may either
be discarded or poured from one jug to another; however, no more
than the initial 5 liters is available.
Sol.
Water jug problem
The state space for this problem can be described as the set of ordered pairs
of integers(x,y)
X represents the number of liter of water in the 5-litre jug and y represents
the number of liter of water in 2-liter jug..
The start state is (5,0). The goal state is (n,1) for any value of n(since the
problem does not specify how many liters need to be in the 2-litre jug.

S,No Current Next state Description


state
1 (x,y) if y < 2 (x,2) Pour water in 2 liter jug y
2 (x,y)if x<5 (5,y) Pour 5 liter in jug x
3 (x,y)if y>0 (x,y-d) Drop water from y jug
4 (x,y)ifx>0 (x-d,y) Drop water from x jug
5 (x,y)if y>0 (x,0) Drop all water out
6 (x,y)ifx>0 (0,y) Drop all water out
7 (x,y)ifx+y<=5 (x-y,y+(x+y) If y is 0 and x contain water then pour water from x->y
Y=0
8 (x,y)ifx+y=1 (0,1) Drop water in the y

X Y
5 0
3 2
3 0
1 2
1 0
0 1

Q3.-Discuss state space representation for the following well-known


problems:

(i) Traveling Salesman Problem


(ii) 8-queen problem

Sol.

a state space representation is a mathematical model of a physical system as a set of


input, output and state variables related by first-order differential equations. To abstract
from the number of inputs, outputs and states, the variables are expressed as vectors,
and the differential and algebraic equations are written in matrix form (the last one can
be done when thedynamical system is linear and time invariant). The state space
representation (also known as the "time-domain approach") provides a convenient and
compact way to model and analyze systems with multiple inputs and outputs.
With p inputs and q outputs, we would otherwise have to write down Laplace
transforms to encode all the information about a system. Unlike the frequency domain
approach, the use of the state space representation is not limited to systems with linear
components and zero initial conditions. "State space" refers to the space whose axes
are the state variables. The state of the system can be represented as a vector within
that space.

(i) Travelling salesman problem

A salesman has a list of cities, each of which he must visit exactly once. There are
direct roads between each pair of cities on the list. Find the route the salesman should
follow for the shortest possible round trip that both starts and finishes at any one of the
cities.
Description
As a graph problem

TSP can be modeled as an undirected weighted graph, such that cities are the graph's vertices, paths are
the graph's edges, and a path's distance is the edge's length. A TSP tour becomes a Hamiltonian cycle,
and the optimal TSP tour is the shortest Hamiltonian cycle. Often, the model is a complete graph(i.e., an
edge connects each pair of vertices). If no path exists between two cities, adding an arbitrarily long edge
will complete the graph without affecting the optimal tour.

Asymmetric and symmetric


In the symmetric TSP, the distance between two cities is the same in each opposite direction, forming
an undirected graph. This symmetry halves the number of possible solutions. In the asymmetric TSP,
paths may not exist in both directions or the distances might be different, forming a directed graph.Traffic
collisions, one-way streets, and airfares for cities with different departure and arrival fees are examples of
how this symmetry could break down.

With metric distances


In the metric TSP, also known as delta-TSP or Δ-TSP, the intercity distances satisfy the triangle
inequality. This can be understood as “no shortcuts”, in the sense that the direct connection from A to B is
never longer than the detour via C:

These edge lengths define a metric on the set of vertices. When the cities are viewed as points in
the plane, many natural distance functions are metrics.

 In the Euclidian TSP the distance between two cities is the Euclidean distance between
the corresponding points.
 In the Rectilinear TSP the distance between two cities is the sum of the differences of
their x- and y-coordinates. This metric is often called the Manhattan distance or city-block
metric.
 In the maximum metric, the distance between two points is the maximum of the
differences of their x- and y-coordinates.

The last two metrics appear for example in routing a machine that drills a given set of holes in
a printed circuit board. The Manhattan metric corresponds to a machine that adjusts first one co-
ordinate, and then the other, so the time to move to a new point is the sum of both movements. The
maximum metric corresponds to a machine that adjusts both co-ordinates simultaneously, so the
time to move to a new point is the slower of the two movements.

Despite the simplification over the general case, the metric TSP problem with an arbitrary metric is
still NP-complete.

Non-metric distances
Distance measures that do not satisfy the triangle inequality arise in many routing problems. For
example, one mode of transportation, such as travel by airplane, may be faster, even though it
covers a longer distance.

In its definition, the TSP does not allow cities to be visited twice, but many applications do not need
this constraint. In such cases, a symmetric, non-metric instance can be reduced to a metric one.
This replaces the original graph with a complete graph in which the inter-city distance cij is replaced
by the shortest path between i and j in the original graph.

Related problems

(ii) 8-queen problem

The problem can be quite computationally expensive as there are 4,426,165,368 (i.e.,
64 choose 8) possible arrangements of eight queens on a 8×8 board, but only 92
solutions. It is possible to use shortcuts that reduce computational requirements or rules
of thumb that avoids brute force computational techniques. For example, just by
applying a simple rule that constrains each queen to a single column (or row), though
still considered brute force, it is possible to reduce the number of possibilities to just
16,777,216 (that is, 88) possible combinations. Generating the permutations that are
solutions of the eight rooks puzzle[1] and then checking for diagonal attacks further
reduces the possibilities to just 40,320 (that is, 8!). These are computationally
manageable for n = 8, but would be intractable for problems of n ≥ 20, as 20! = 2.433 *
1018. Extremely interesting advancements for this and other toy problems is the
development and application of heuristics (rules of thumb) that yield solutions to
the n queens puzzle at an astounding fraction of the computational requirements.

This heuristic solves N queens for any N ≥ 4. It forms the list of numbers for vertical
positions (rows) of queens with horizontal position (column) simply increasing. N is 8 for
eight queens puzzle.

1. If the remainder from dividing N by 6 is not 2 or 3 then the list is simply all
even numbers followed by all odd numbers ≤ N
2. Otherwise, write separate lists of even and odd numbers (i.e. 2,4,6,8 -
1,3,5,7)
3. If the remainder is 2, swap 1 and 3 in odd list and move 5 to the end
(i.e. 3,1,7,5)
4. If the remainder is 3, move 2 to the end of even list and 1,3 to the end of
odd list (i.e. 4,6,8,2 - 5,7,9,1,3)
5. Append odd list to the even list and place queens in the rows given by
these numbers, from left to right (i.e. a2, b4, c6, d8, e3, f1, g7, h5)

For N = 8 this results in the solution shown above. A few more examples follow.

 14 queens (remainder 2): 2, 4, 6, 8, 10, 12, 14, 3, 1, 7, 9, 11, 13, 5.


 15 queens (remainder 3): 4, 6, 8, 10, 12, 14, 2, 5, 7, 9, 11, 13, 15, 1, 3.
 20 queens (remainder 2): 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 1, 7, 9, 11, 13, 15,
17, 19, 5.

Solutions to the 8-Queens Problem

This problem is to place 8 queens on the chess board so that they do not check each other. This
problem is probably as old as the chess game itself, and thus its origin is not known, but it is
known that Gauss studied this problem. If we want to find a single solution, it is not difficult as
shown below. If we want to find all possible solutions, the problem is difficult and the backtrack
method is the only known method. For 8-queen, we have 92 solutions. If we exclude symmetry,
there are 12 solutions.

Consider the general case of the n-Queens Problem

If n is a prime number, a solution is easily found by drawing a straight line in the (n, n) finite
plane. Since no two straight lines can intersect at two points, a straight line y=ax+b where a is
not equal to 1 or -1 can give a solution. Coordinates start from 0.

Example 1: n = 7, y = 2x
6 X
5 X
4 X
3 X
2 X
1 X
0 X
0 1 2 3 4 5 6

n = 7, y = 3x + 1
6 X
5 X
4 X
3 X
2 X
1 X
0 X
0 1 2 3 4 5 6

We can easily find 28 solutions by a=2, 3, 4, 5, and b=0, 1, 2, 3, 4, 5, 6.

The ratio of analytical solutions for the total solutions for some small p is as follows:

p=5, 10/10, 100%

p=7, 28/40, 70%

p=11, 99/2680, 4%

For composite numbers n=pq, we can make a direct product of the p-queen and q-queen
problems. That is, each queen position of the p-queen problem is regarded as a solution of the q-
queen problem. We can change the roles of p and q. Thus for 35=5*7, we can generate
10*(40)^5 + 40*(10)^7 solutions.

To generate one solution for a general n, let the plane coordinated by i=0, ..., n-1 and j=0, ..., n-1.

Suppose n is even. For any k,

(1) If n is not 6k+2,

j = 2i+1, for 0 <= i < n/2


j = 2i mod n, for n/2 <= i < n

Example 2. n=6

5 X
4 X
3 X
2 X
1 X
0 X
0 1 2 3 4 5

(2) If n is not 6k

j = (n/2 + 2i -1) mod n, for 0 <= i < n/2


j = (n/2 + 2i + 2) mod n, for n/2 <= i

Example 3. n=8

7 X
6 X
5 X
4 X
3 X
2 X
1 X
0 X
0 1 2 3 4 5 6 7

For odd numbers, we can attach a queen at (n-1, n-1).

Example 4. n=9

7 X
7 X
6 X
5 X
4 X
3 X
2 X
1 X
0 X
0 1 2 3 4 5 6 7

The eight queens problem is frequently used as an example in Artificial Intelligence courses. The
object is to place eight queens on an empty chess board so that none of them can take the other.

Part-B

Q4 Write a program to implement :

• Breath –First Search


• Depth –First Serach
Sol. Algorithm: Breadth-first search
Step1. Create a variable called NOdE-LIST and set it to the initial state.
Step2. Until a goal state is found or NODE-LIST is empty.
(a) Remove the first element from NODE-LIST and call it E. If NODE-LIST
was empty, quit.
(b)For each way that each rule can match the state described in E do:
(i) Apply the rule to generate a new state.
(ii) If the new state is a goal state, quit and return this state.
(iii) Otherwise, add the new state to the end of NODE-LIST.

#include<iostream.h>

class Queue
{
private:
int data;
Queue*next;
public:
void Enque(int);
int Deque();
}*head,*tail;
void Queue::Enque(int data)
{
Queue *temp;
temp=new Queue;
temp->data=data;
temp->next=NULL;
if(head==NULL)
head=temp;
else
tail->next=temp;
tail=temp;
}
int Queue::Deque()
{
Queue* temp;
temp=head;
head=head->next;
return temp->data;
}

int visit[100];
int bfs_span_tree[100][100];

class graph
{
private:
int a;
graph*next;
public:
void bfs();
graph* create(graph*);
void ftraverse(graph*);
};

graph* graph::create(graph*head)
{
int a;
graph*last;
head=last=NULL;
graph*temp;
cout<<”Enter adjecent node ,-1 to stop:\n”;
cin>>a;
while(a!=-1)
{
temp=new graph;
temp->a=a;
temp->next=NULL;
if(head==NULL)
head=temp;
else
last->next=temp;
last=temp;
cout<<”Enter adjecent node ,-1 to stop:\n”;
cin>>a;
}
return head;
}

void graph::ftraverse(graph*h)
{
while(h!=NULL)
{
cout<<h->a<<”->”;
h=h->next;
}
cout<<”NULL\n”;
}

void graph::bfs()
{
cout<<”******************************************************
****\n”;
cout<<”This program is to implement bfs for an unweighted graph \n”;
cout<<”******************************************************
****\n”;

graph *ptr[100];
int n;
cout<<”Enter the no. of nodes in the grph:”;
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<”Enter the adjacent nodes to node no. “<<i<<endl;
cout<<”***************************************\n”;
ptr[i]=create(ptr[i]);
}
cout<<”\n\nThe Entered Graph is ::\n”;
for(i=1;i<=n;i++)
{
cout<<”< “<<i<<” > ::”;
ftraverse(ptr[i]);
}

int x;
cout<<”\nEnter the start node <1,…”<<n<<”>:”;
cin>>x;
cout<<”\n\nThe Breadth first search traversal is:\n”;
Queue object;

//Mark all the nodes as not viseted


for(i=1;i<=n;i++)
{
visit[i]=0;
}
for(i=1;i<=n;i++)
for(int j=1;j<=n;j++)
bfs_span_tree[i][j]=0;
//Enque the start node
object.Enque(x);

int p;
while(head!=NULL&&tail!=NULL)
{
//Deque a node
p=object.Deque();
int x=p;
//If it is not visited yet

while(ptr[p]!=NULL)
{
if(visit[ptr[p]->a]!=1)
{
cout<<”node “<<ptr[p]->a<<” is visited\n”;
//Mark the node as visited
visit[ptr[p]->a]=1;
bfs_span_tree[ptr[p]->a][x]=1;
}
//Enque all its adjacent nodes
object.Enque(ptr[p]->a);
ptr[p]=ptr[p]->next;
}

cout<<”\n\nThe required bfs spanning tree is ::\n\n”;


for(i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cout<<bfs_span_tree[i][j]<<’ ‘;
cout<<endl;
}

cout<<endl;
}
int main()
{
graph obj;
obj.bfs();
return 0;
}

Algorithm :Depth- first search


Step 1: If the initial state is a goal state, quit and return success.
Step2: otherwise, do the following until success or failure is signaled:
(a) Generate a successor, E of the initial state. If there are no more
successors, signal failure.
(b)Call Depth-First search with E as the initial state.
(c) If success is returned, signal success. Otherwise continue in this loop.

#include <stdio.h>

typedef struct node {


int value;
struct node *right;
struct node *left;
} mynode;

mynode *root;

add_node(int value);

void levelOrderTraversal(mynode *root);

int main(int argc, char* argv[]) {


root = NULL;

add_node(5);
add_node(1);
add_node(-20);
add_node(100);
add_node(23);
add_node(67);
add_node(13);

printf("\n\n\nLEVEL ORDER TRAVERSAL\n\n");


levelOrderTraversal(root);

getch();
}

// Function to add a new node...


add_node(int value) {
mynode *prev, *cur, *temp;

temp = malloc(sizeof(mynode));
temp->value = value;
temp->right = NULL;
temp->left = NULL;

if(root == NULL) {
printf("\nCreating the root..\n");
root = temp;
return;
}

prev = NULL;
cur = root;

while(cur != NULL) {
prev = cur;
//cur = (value < cur->value) ? cur->left:cur->right;
if(value < cur->value) {
cur = cur->left;
} else {
cur = cur->right;
}
}

if(value < prev->value) {


prev->left = temp;
} else {
prev->right = temp;
}
}

// Level order traversal..


void levelOrderTraversal(mynode *root) {
mynode *queue[100] = {(mynode *)0}; // Important to initialize!
int size = 0;
int queue_pointer = 0;

while(root) {
printf("[%d] ", root->value);
if(root->left) {
queue[size++] = root->left;
}

if(root->right) {
queue[size++] = root->right;
}
root = queue[queue_pointer++];
}
}

Q5. Discuss ways in which an h function might be improved during a


search.

Sol.

A heuristic function or simply a heuristic is a function that ranks alternatives in


various search algorithms at each branching step basing on an available
information in order to make a decision which branch is to be followed during a
search.

Within the state space search paradigm there are several ways to
bring domain knowledge to bear, thereby improving the search
process to cut down on the time or the space required, or both.
Two approaches that are often used are

(a) developing a better heuristic function and

(b) pruning the search tree during the search process. Let’s see
how each of these can be applied

1. Identify obvious inefficiencies in the current algorithm.

2. Apply this insight to actual steps in the search process.


3. Formulate an a strategy/algorithm.

4. Implement this in code.

Effect of heuristics on computational performance

In any searching problem where there are b choices at each node and a depth of d at the goal
node, a naive searching algorithm would have to potentially search around bd nodes before
finding a solution. Heuristics improve the efficiency of search algorithms by reducing the
branching factor from b to a lower constant b', using a cutoff mechanism. The branching factor
can be used for defining a partial order on the heuristics, such that h1(n) < h2(n) if h1(n) has a
lower branch factor than h2(n) for a given node n of the search tree. Heuristics giving lower
branching factors at every node in the search tree are preferred for the resolution of a particular
problem, as they are more computationally efficient.

Q6. How does Breath- First Search would work better than Depth –
First search and vice-versa?

Sol.

Advantages of Depth-First Search are as follows


¤ DFS is space ecient: it may store only those states currently in the
search stack.
¤ Counterexamples are easily constructed: when a violation to the pro-
perty is found, a counterexample can be obtained straightforwardly
from the content of the search stack.
¤ DFS can be easily extended to detect cycles and thus check liveness
properties.

A disadvantage of Depth-First Search is that counterexamples constructed


from the search stack may be too long to comprehend. On the contrary,
counterexamples found by Breadth-First-Search are always the shortest.

However, BFS has the following disadvantages


¤ BFS is less space ecient.
¤ BFS cannot be easily extended to check liveness properties.
¤ Counterexamples cannot be obtained directly from the queue.
These disadvantages are due to the use of queues that store all the states
at some level and do not contain any path information
11 Nov 2010 Avneet Kaur Dhawan
Date: Sig. of Faculty member

Vous aimerez peut-être aussi