Read the discussion on the Monkey Puzzle in the accompanying file. The Decision
ID: 3919245 • Letter: R
Question
Read the discussion on the Monkey Puzzle in the accompanying file. The Decision form of this problem is NP-Complete. You are to solve the optimization form of this puzzle that contains 25 tiles, that is in which you are presented with a 5 x 5 grid and the 25 "monkey tiles" are placed randomly into this grid Tile positioning may be changed but tiles may not be rotated. Assume that there are five monkey colors in total and that monkey top-halves and bottom-halves have been randomly placed over the 25 tiles but the quantity of each should be the same. Use a Genetic Algorithm to solve this puzzle. Experiment with various population sizes. C++ or C please
Explanation / Answer
/*
* C++ Program to Solve N-Monkey Problem
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define N 5
using namespace std;
/* print solution */
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
}
/* check if a Monkey can be placed on board[row][col]*/
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
{
if (board[row][i])
return false;
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j])
return false;
}
for (i = row, j = col; j >= 0 && i < N; i++, j--)
{
if (board[i][j])
return false;
}
return true;
}
/*solve N Monkey problem */
bool solveNQUtil(int board[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++)
{
if ( isSafe(board, i, col) )
{
board[i][col] = 1;
if (solveNQUtil(board, col + 1) == true)
return true;
board[i][col] = 0;
}
}
return false;
}
/* solves the N Monkey problem using Backtracking.*/
bool solveNQ()
{
int board[N][N] = {0};
if (solveNQUtil(board, 0) == false)
{
cout<<"Solution does not exist"<<endl;
return false;
}
printSolution(board);
return true;
}
// Main
int main()
{
solveNQ();
return 0;
}
============================================ OUTPUT ===========
1 0 0 0 0
0 0 0 1 0
0 1 0 0 0
0 0 0 0 1
0 0 1 0 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.