Write a C++ program called coin collection.cpp to collect maximum number of coin
ID: 3716942 • Letter: W
Question
Write a C++ program called coin collection.cpp to collect maximum number of coins on an n x m board with inaccessible cells Your program should ask a user for a text filename to read a 2-D array of a sequence of numbers. In the array, 1 indicates that there's a coin on the cell, while 0 means no coin. A cell with the number 2 indicates that the cell is not accessible. Your program should display maximum possible coins and path to collect it. If you have more than one path, you only need to display one. You can assume that the board size is less than or equal to 25 x 25 This is a sample run of the program $ gt+-o coin collection coin collection.cpp $ . /coin collection Enter a file name: ./t1.txt Max coins: 3 Path: (1,1)-> (2,1)-> (2,2) -> (3,2)- (3,3)-> (4,3) -> (4,4) For the sample run, t1.txt has the following context 1 2 01 The first line (= 4 and 4 in the example) indicates the numbers of rows and columns in the file. One blank space is used to delimiter the data. Note that there's no blank space at the end of each line. If your program does not read the file properly, your program will get no credit. In the sample execution, the starting indexes of the path are 1, not 0 This is another sample run $ gtt -o coin_collection coin_collection.cpp $ . /coin collection Enter a file name: ./t2.txt Max coins: 1 Path: (1,1)-> (1,2) -> (1,3)-> (1,4)-> (2,4) For the sample run, t2.txt has the following contextExplanation / Answer
The below coding can help you.coin_collection.cpp
#include<iostream.h>
#include <fstream>
#include<string.h>
using namespace std;
#define r 4
#define c 4
bool isPossible(int i, int j)
{
return (i >=0 && i < r && j >=0 && j < c);
}
int maxCoins(int array[r][c], int i, int j, int direction)
{
if (isPossible(i,j) == false || array[i][j] == 2)
return 0;
int result = (array[i][j] == 1)? 1: 0;
if (direction == 1)
return result+ max(maxCoins(array, i+1, j, 0),
maxCoins(array, i, j+1, 1));
return result+max(maxCoins(array, i+1, j, 1),
maxCoins(array, i, j-1, 0));
}
int main()
{
int array[r][c];
ifstream inFile;
string inFileName = "Give your own file name with specific path";
inFile.open(inFileName);
if(!inFile){
cout<<"Error in opening the file"<<endl;}
else{
array[r][c]<<inFile;//the values are assigned from the file
cout << "Maximum number of collected coins is "
<< maxCoins(array, 0, 0, 1);
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.