Sei sulla pagina 1di 10

1.

Prueba lo siguiente: para un árbol con factor de ramificación constante grande b, casi
todos los nodos están es el último nivel de profundidad d. Muestra además que esto no es
siempre cierto cuando el f.r. efectivo es grande pero no constante.

Si b no fuera constante, el factor de ramificación seria mucho mas grande.

2. Calcula el f.r. promedio para el problema del puzzle-8 sin chequear los ciclos. El f.r.
promedio es el f.r. que tendría un árbol de igual número de nodos en el último nivel, f.r.
constante e igual de profundo. Calcula además el f.r. promedio para el puzzle-8 con
búsqueda no uniforme mientras se evitan los ciclos de longitud 2.

b= 8

Si d=2

Factor promedio:

: 8^3/4*2=8^3/2=2.86

Factor de ramificación efectivo

8^2/2=8

3. ¿cuál es la diferencia entre el f.r. promedio y el efectivo?

El factor de ramificación efectivo es el valor que nosotros tomamos de todo los nodos,
mientras el factor de ramificación promedio es la mejor solución.

4. ¿Por qué el f.r. efectivo encaja mejor para análisis y comparación del tiempo de
computación de algoritmos de búsqueda que el f.r. promedio?

Porque obtenemos el mejor y el peor de los casos, pero si es comparación del tiempo; el
factor de ramificación promedio tiene mejor tiempo que el factor de ramificación efectivo.

5. Muestre que para un árbol de ramificación pesado con n nodos y profundidad d, el f.r
efectivo raíz de d de n es aproximadamente igual al f.r. Promedio, así es igual a

Si el número total de nodos generados es N y la profundidad de la solución es d, entonces


b* con N nodos^2. Esta medida representa el número medio de caminos intentados para
cada estado. Si el factor de ramificación efectivo fuera 1, nuestro camino de búsqueda
obtenido por el algoritmo sería un camino solución. Es decir, cuando más se aproxima a 1
muestra heurística, la búsqueda estará más dirigida al objetivo, con muy pocas
ramificaciones en el árbol. Normalmente, para una heurística, b* es más o menos
constante en varias instancias del problema.

6. Calcula el tamaño del espacio de estados para un problema del puzzle-8, para el análogo
problema puzzle-3 (matriz 2x2), así como para el problema puzzle-15 (matriz 4x4).

Puzzle-8=8^7=2097152
Puzzle-3=81
Puzzle-15=6.56840835e^18

7. Prueba que el gráfico de estados consiste en estados (nodos) y acciones (enlaces) para el
puzzle-3 cae en 2 grafos conectados entre los cuales no hay conexiones.

8. Con la búsqueda por amplitud del puzzle-8, halla un camino (manualmente) desde el nodo
inicial
hasta el nodo final usando la heurística
h1 y la heurística h2

Heuritica:

#piezas fuera de sitito=7

Movimientos necesarios o distancia de Manhattan=12

Manual
9. Implementa los algoritmos de breadth-first search, depth-first search y iterative deeping
en el lenguaje que prefieras y pruebalos con el ejemplo del puzzle-8. ¿por qué tiene poco
sentido usar la búsqueda en profundidad en puzzle-8?

breadth-first search

import java.util.*;

class EightPuzzle {

Queue<String> q = new LinkedList<String>(); // Use of Queue


Implemented using LinkedList for Storing All the Nodes in BFS.
Map<String,Integer> map = new HashMap<String, Integer>(); //
HashMap is used to ignore repeated nodes

public static void main(String args[]){

String str="087465132"; //
Input the Board State as a String with 0 as the Blank Space
EightPuzzle e = new EightPuzzle(); // New
Instance of the EightPuzzle
e.add(str,0);
// Add the Initial State

while(e.q.peek()!=null){

e.up(e.q.peek());
// Move the blank space up and add new state to queue
e.down(e.q.peek());
// Move the blank space down
e.left(e.q.peek());
// Move left
e.right(e.q.remove());
// Move right and remove the current node from Queue
}
System.out.println("Solution doesn't exist");
}

//Add method to add the new string to the Map and Queue
void add(String str,int n){
if(!map.containsKey(str)){
map.put(str,n);
q.add(str);
}
}

/* Each of the Methods below Takes the Current State of Board as


String. Then the operation to move the blank space is done if
possible.
After that the new string is added to the map and queue.If
it is the Goal State then the Program Terminates.
*/
void up(String str){
int a = str.indexOf("0");
if(a>2){
String s = str.substring(0,a-3)+"0"+str.substring(a-
2,a)+str.charAt(a-3)+str.substring(a+1);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("Solution Exists at Level
"+map.get(s)+" of the tree");
System.exit(0);
}
}
}
void down(String str){
int a = str.indexOf("0");
if(a<6){
String s =
str.substring(0,a)+str.substring(a+3,a+4)+str.substring(a+1,a+3)+"0"+s
tr.substring(a+4);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("Solution Exists at Level
"+map.get(s)+" of the tree");
System.exit(0);
}
}
}
void left(String str){
int a = str.indexOf("0");
if(a!=0 && a!=3 && a!=6){
String s = str.substring(0,a-1)+"0"+str.charAt(a-
1)+str.substring(a+1);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("Solution Exists at Level
"+map.get(s)+" of the tree");
System.exit(0);
}
}
}
void right(String str){
int a = str.indexOf("0");
if(a!=2 && a!=5 && a!=8){
String s =
str.substring(0,a)+str.charAt(a+1)+"0"+str.substring(a+2);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("Solution Exists at Level
"+map.get(s)+" of the tree");
System.exit(0);
}
}
}
}

depth-first search

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
class EightPuzzle {

Queue<String> agenda = new LinkedList<String>(); // Use of Queue


Implemented using LinkedList for Storing All the Nodes in BFS.
Map<String,Integer> stateDepth = new HashMap<String, Integer>(); // HashMap
is used to ignore repeated nodes
Map<String,String> stateHistory = new HashMap<String,String>(); // relates
each position to its predecessor

public static void main(String args[]){

String str="087465132"; // Input the


Board State as a String with 0 as the Blank Space

EightPuzzle e = new EightPuzzle(); // New Instance of the


EightPuzzle
e.add(str, null); //
Add the Initial State

while(!e.agenda.isEmpty()){
String currentState = e.agenda.remove();
e.up(currentState); // Move
the blank space up and add new state to queue
e.down(currentState); // Move
the blank space down
e.left(currentState); // Move
left
e.right(currentState); // Move right and
remove the current node from Queue
}

System.out.println("Solution doesn't exist");


}

//Add method to add the new string to the Map and Queue
void add(String newState, String oldState){
if(!stateDepth.containsKey(newState)){
int newValue = oldState == null ? 0 : stateDepth.get(oldState) + 1;
stateDepth.put(newState, newValue);
agenda.add(newState);
stateHistory.put(newState, oldState);
}
}

/* Each of the Methods below Takes the Current State of Board as String.
Then the operation to move the blank space is done if possible.
After that the new string is added to the map and queue.If it is the Goal
State then the Program Terminates.
*/
void up(String currentState){
int a = currentState.indexOf("0");
if(a>2){
String nextState = currentState.substring(0,a-
3)+"0"+currentState.substring(a-2,a)+currentState.charAt(a-
3)+currentState.substring(a+1);
checkCompletion(currentState, nextState);
}
}

void down(String currentState){


int a = currentState.indexOf("0");
if(a<6){
String nextState =
currentState.substring(0,a)+currentState.substring(a+3,a+4)+currentState.sub
string(a+1,a+3)+"0"+currentState.substring(a+4);
checkCompletion(currentState, nextState);
}
}
void left(String currentState){
int a = currentState.indexOf("0");
if(a!=0 && a!=3 && a!=6){
String nextState = currentState.substring(0,a-
1)+"0"+currentState.charAt(a-1)+currentState.substring(a+1);
checkCompletion(currentState, nextState);
}
}
void right(String currentState){
int a = currentState.indexOf("0");
if(a!=2 && a!=5 && a!=8){
String nextState =
currentState.substring(0,a)+currentState.charAt(a+1)+"0"+currentState.substr
ing(a+2);
checkCompletion(currentState, nextState);
}
}

private void checkCompletion(String oldState, String newState) {


add(newState, oldState);
if(newState.equals("123456780")) {
System.out.println("Solution Exists at Level
"+stateDepth.get(newState)+" of the tree");
String traceState = newState;
while (traceState != null) {
System.out.println(traceState + " at " +
stateDepth.get(traceState));
traceState = stateHistory.get(traceState);
}
System.exit(0);
}
}

10. Muestra que el algoritmo de búsqueda por amplitud, dado costo constante para todas las
acciones, es garantizado que encontrará la solución más corta. Además muestra que esto
no es el caso para costos variables.

BFS(grafo G, nodo_fuente s)
{
// recorremos todos los vértices del grafo inicializándolos a
NO_VISITADO,
// distancia INFINITA y padre de cada nodo NULL
for u ∈ V[G] do
{
estado[u] = NO_VISITADO;
distancia[u] = INFINITO; /* distancia infinita si el nodo no
es alcanzable */
padre[u] = NULL;
}
estado[s] = VISITADO;
distancia[s] = 0;
Encolar(Q, s);
while !vacia(Q) do
{
// extraemos el nodo u de la cola Q y exploramos todos sus
nodos adyacentes
u = extraer(Q);
for v ∈ adyacencia[u] do
{
if estado[v] == NO_VISITADO then
{
estado[v] = VISITADO;
distancia[v] = distancia[u] + 1;
padre[v] = u;
Encolar(Q, v);
}
}
}
}

Falta recorrer vértices no adyacentes directa o indirectamente al vértice pues la cola


queda vacía sin los adyacentes restantes.

11. Usando la búsqueda A* para puzzle-8, busca manualmente un camino desde el nodo
inicial hasta el nodo final usando la heurística
h1 y la heurística h2

12. Construye el árbol de búsqueda A* para el grafo de ciudades de Ulm y sus alrededores
(slide 31) y usa la distancia de vuelo entre Ulm y las otras ciudades como heurística. Inicia
en Bern con Ulm como destino. Cuida que cada ciudad solo aparezca una vez en el
camino.

13. Implementa la búsqueda A* en el lenguaje de programación de tu dominio usando las


heurísticas h1 y h2 y pruébalas con el ejemplo del puzzle-8

El algoritmo Beam
1. Primero se tiene que definir el valor w. El valor w es el que indicará cuántos hijos o
estados siguientes mejores se tendrá como candidatos para hallar la solución. El valor
depende del solucionador del problema. No está demás decir que si el valor w es mayor o
igual que todos los estados el algoritmo funcionará como un algoritmo normal de
búsqueda en anchura, puesto que se están seleccionando todos los hijos y por lo tanto no
está relacionado ninguna PODA.
2. Se tiene que limitar el algoritmo el número de niveles que tiene que explorar. Una vez
terminado todos los niveles tiene que revisar todos los nodos generados cuando llego al
último nivel. Lo anterior se conoce como BackTracking.
3. Principio de Programación Dinámica, se basa en que si ya hay un nodo generado no
repetirlo porque estaría cayendo en un ciclo.

14. Da una función de evaluación heurística para estados en los cuales HeuristicSearch puede
ser implementado como depth-first search y una para una implementación de breadth-
firtst search.

15. ¿cuál es la relación entre la imagen de la pareja en el cañon (la flor) y una heurística
admisible?

Que una personas se quede hablando al niño, y el otro dar la vuelta y recoger al niño,
siempre y cuando la personas que se quede no haga caer al niño.

16. Muestre que las heurísticas h1 y h2 para el puzzle-8 son admisibles.

Si vemos el tiempo con la h1 y la h2 es cada vez menor.

17. El árbol de búsqueda para el juego de 2 jugadores dado en el siguiente slide con los rangos
de todos los nodo hojas. Use la búsqueda minMax con alpha-beta pruning de izquierda a
derecha. Cruza todos los nodos que no son visitados y da un rating resultado óptimo para
cada nodo interno. Marca el camino elegido.

Potrebbero piacerti anche