Docsity

Data Structures & Algorithms: Search, Puzzles, & Games, Cheat Sheet of Artificial Intelligence

Toggle sidebar
bg1
DFS BFS DLS
#include<stdio.h>
#include<stdlib.h>
int queue[100];
int front=0;
int rear=-1;
struct node{
int data;
struct node *left;
struct node *right;
};
/**Insert data in the tree**/
struct node *insert(struct node *root, int value)
{
if(root == NULL)
{
root = (struct node*) malloc(sizeof(struct node));
root->left = root->right = NULL;
root->data = value;
return root;
}
else
{
if(value < root->data)
{
root->left = insert(root->left, value);
}
else
{
if(value > root->data)
{
root->right = insert(root->right, value);
}
}
return root;
}
};
void printNode(struct node *root){
if(root != NULL) {
printf("%d ", root->data);
}
}
/******** Queue ********/
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Data Structures & Algorithms: Search, Puzzles, & Games and more Cheat Sheet Artificial Intelligence in PDF only on Docsity!

DFS BFS DLS

#include<stdio.h> #include<stdlib.h> int queue[100]; int front=0; int rear=-1; struct node{ int data; struct node left; struct node right; }; /Insert data in the tree**/ struct node *insert(struct node root, int value) { if(root == NULL) { root = (struct node) malloc(sizeof(struct node)); root->left = root->right = NULL; root->data = value; return root; } else { if(value < root->data) { root->left = insert(root->left, value); } else { if(value > root->data) { root->right = insert(root->right, value); } } return root; } }; void printNode(struct node *root){ if(root != NULL) { printf("%d ", root->data); } } /******** Queue ********/

void enqueue(struct node root){ if(root != NULL){ rear++; queue[rear] = root; } } void dequeue(){ if(rear>=front){ struct node root = queue[front]; printNode(root); front++; enqueue(root->left); enqueue(root->right); } } / BFS function / void bfs(struct node root){ if(root != NULL){ enqueue(root); do{ dequeue(root); }while(front <= rear); } } /DFS function / void dfs(struct node root){ if(root != NULL){ dfs(root->left); dfs(root->right); printf("%d ", root->data); } } /DLS function/ void dls(struct node *root, int i, int limit){ for(i = 0; i < limit; i++){ if(root != NULL){ if(limit > 0){ dls(root->left, i, limit-1 ); dls(root->right, i, limit-1 ); printf("%d ", root->data); } } //printf("\n");

Eight Puzzle

#include<stdio.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include<time.h> #define r 3 #define c 3 char matrix[r][c]; char new[r][c]; int count; char final[r][c] = {{'1','2','3'},{'4','5','6'},{'7','8',' '}}; int i,j; char z ; int p,q,x,y; int t =0; int result = 0; void load(){ for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(new[i][j] == '0'){ matrix[i][j]= ' '; continue; } matrix[i][j]= new[i][j]; } } } void blank(){ for(i=0;i<3;i++){ for(j=0;j<3;j++){ new[i][j]= ' '; } } } int main(){ time_t T= time(NULL); struct tm tm = *localtime(&T);

char f[4]; int rsl ; int random,t; int randvalues[9]; main: count = 0; blank(); T= time(NULL); tm = *localtime(&T); srand(tm.tm_sec); while(count!=9){ rsl=rand()%9; sprintf(f,"%d",rsl); for(i=0;i<r;i++){ for(j=0;j<c;j++){ if((new[i][j]) == f[0]){ i = 4; j = 4; continue; } else if((new[i][j]) == ' '){ new[i][j] = f[0]; i = 4; j = 4; count++; } } } } load(); for(i=0;i<r;i++){ for(j=0;j<c;j++){ printf("|%c|",matrix[i][j]); } printf("\n"); } while(1){ printf("enter value to change its position to blank space\n"); scanf(" %c",&z); if(z=='q'){ printf("\n*****You Quit*****\n"); goto main; // break; } for(i=0;i<r;i++){ for(j=0;j<c;j++){

for(i=0;i<r;i++){ for(j=0;j<c;j++){ printf("|%c|",matrix[i][j]); } printf("\n"); } if(t==9){ printf("\n****you Win****\n"); break; } } return 1; }

Water Jug

from collections import defaultdict jug1, jug2, aim = 4, 3, 2 visited = defaultdict(lambda: False) def waterJugSolver(amt1, amt2): if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0): print(amt1, amt2) return True if visited[(amt1, amt2)] == False: print(amt1, amt2) visited[(amt1, amt2)] = True return (waterJugSolver(0, amt2) or waterJugSolver(amt1, 0) or waterJugSolver(jug1, amt2) or waterJugSolver(amt1, jug2) or waterJugSolver(amt1 + min(amt2, (jug1-amt1)), amt2 - min(amt2, (jug1-amt1))) or waterJugSolver(amt1 - min(amt1, (jug2-amt2)), amt2 + min(amt1, (jug2-amt2)))) else: return False print("Steps: ") waterJugSolver(0, 0)

Towers of Hanoi

#include <bits/stdc++.h> using namespace std; void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 1) { cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod<<endl; return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl; towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } int main() { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; }

Farmer Goat Problem

farmer,goat,cabbage,wolf=("farmer","goat","cabbage","wolf") carryables=(goat,cabbage,wolf,None) forbiddens=(set((goat,cabbage)), set((wolf,goat))) def mayhem(cfg): for shore in cfg[0]: if farmer not in shore: for forbidden in forbiddens: if shore.issuperset(forbidden): return True return False def done(cfg): left,right=cfg[0] return left==set() def ferry(cfg,item): left,right=[set(x) for x in cfg[0]] if farmer in left: src,dst=left,right else: src,dst=right,left if item and not item in src:

Tic Tac Toe

import numpy as np import random from time import sleep def create_board(): return(np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])) def possibilities(board): l = [] for i in range(len(board)): for j in range(len(board)): if board[i][j] == 0: l.append((i, j)) return(l) def random_place(board, player): selection = possibilities(board) current_loc = random.choice(selection) board[current_loc] = player return(board) def row_win(board, player): for x in range(len(board)): win = True for y in range(len(board)): if board[x, y] != player: win = False continue if win == True: return(win) return(win) def col_win(board, player): for x in range(len(board)): win = True for y in range(len(board)): if board[y][x] != player: win = False continue

if win == True: return(win) return(win) def diag_win(board, player): win = True y = 0 for x in range(len(board)): if board[x, x] != player: win = False if win: return win win = True if win: for x in range(len(board)): y = len(board) - 1 - x if board[x, y] != player: win = False return win def evaluate(board): winner = 0 for player in [1, 2]: if (row_win(board, player) or col_win(board,player) or diag_win(board,player)): winner = player if np.all(board != 0) and winner == 0: winner = - return winner def play_game(): board, winner, counter = create_board(), 0, 1 print(board) sleep(2) while winner == 0: for player in [1, 2]: board = random_place(board, player) print("Board after " + str(counter) + " move") print(board) sleep(2) counter += 1 winner = evaluate(board) if winner != 0:

dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {"dZ2": dZ2, "dW2": dW2, "db2": db2, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients def updateParameters(parameters, gradients, learningRate): parameters["W1"] = parameters["W1"] - learningRate * gradients["dW1"] parameters["W2"] = parameters["W2"] - learningRate * gradients["dW2"] parameters["b1"] = parameters["b1"] - learningRate * gradients["db1"] parameters["b2"] = parameters["b2"] - learningRate * gradients["db2"] return parameters X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) Y = np.array([[0, 0, 0, 1]]) neuronsInHiddenLayers = 2 inputFeatures = X.shape[0] outputFeatures = Y.shape[0] parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures) epoch = 100000 learningRate = 0. losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) X = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) cost, _, A2 = forwardPropagation(X, Y, parameters) prediction = (A2 > 0.5) * 1. print('A B | AND') print('____________') for j in range(4): print(str(X[0][j])+" "+str(X[1][j])+" | "+str(int(prediction[0][j])))