SlideShare a Scribd company logo
Write a C++ program which generates and displays a random walk across a grid. A 2-
dimensional array of characters will be used for this grid. The cells visited by the walk will be
labeled by capital letters with A being the first cell, B the cell moved to from A, and so on,
ending either when Z is reached or when it is not possible to move to another cell.
The following libraries, constant definition, and type definition are needed in the program:
#include
#include // for srand and rand
#include // for time
using namespace std;
const int SIZE = 10;
typedef char Grid[SIZE][SIZE]
The grid must be set to have all its elements be the character ’.’ before the walk is begun.
The program must contain the following function prototypes, the main function, and the function
definitions for all the other functions:
// Function prototypes
bool can_move_up(int i, int j, Grid walk);
bool can_move_down(int i, int j, Grid walk);
bool can_move_left(int i, int j, Grid walk);
bool can_move_right(int i, int j, Grid walk);
void init_array(Grid walk);
void generate_random_walk(Grid walk);
void print_array(Grid walk);
int main(void)
{
Grid walk; // the grid in which the random walk occurs
srand((unsigned) time(NULL));
init_array(walk);
generate_random_walk(walk);
print_array(walk);
return 0;
}
The four functions can_move _* must return whether or not it is possible to move in the
particular direction in the grid. For example, a function call like if (can_move_up(i, j, walk))
could be used to determine whether or not it is possible to move up. The rule for a move being
possible is that if it doesn’t go outside of the grid and isn’t already part of the walk, then that
move is possible. The function init_array must set all characters in the grid to ’.’
The function generate_random_walk must modify the cells of grid by changing ones that are
part of the walk to letters.
The function print_array must print the resulting grid in the form shown in the sample run
below.
In the function generate_random_walk, at each step of the walk, randomly select one of the 4
directions and try to move in that direction. If that move isn’t available, try the other moves in
turn until one is possible. If all 4 directions are blocked, the walk must terminate, and the
program must continue and print out the walk. To select one of the 4 directions randomly, use
the expression: rand() % 4
The function rand returns an integer, and finding the remainder of this integer divided by 4
results in getting one of the numbers 0, 1, 2, or 3. Use these 4 numbers to represent the 4
directions up, down, left and right.
The call to the function srand from the main function seeds the pseudo-random number
generator used by rand so that different sequences of numbers will be generated by calls to rand
each time the program is run.
Solution
#include //input output functions in C++
#include //rand() and srand() functions
#include //time() function for creating seed
#include
#include // for srand and rand
#include // for time
using namespace std;
class Grid_Walk
{
const int SIZE = 10;
#define UP 0 //flag for up
#define DOWN 1 //flag for down
#define LEFT 2 //flag for left
#define RIGHT 3 //flag for right
#define DOT '.'//flag for dot
public:
void init_array(Grid_Walk walk);
void generate_random_walk(Grid_Walk walk);
void print_array(Grid_Walk walk);
bool can_move_up(int i, int j, Grid_Walk walk);
bool can_move_down(int i, int j, Grid_Walk walk);
bool can_move_left(int i, int j, Grid_Walk walk);
bool can_move_right(int i, int j, Grid_Walk walk);
};
//Member function definitions
void Grid_Walk:: init_array(Grid_Walk walk)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
walk[i][j] = DOT; // Xcode gives me error for '=' "Expected unqualified-id"
walk[0][0] = 'A'; // Xcode gives me error for '=' "Expected unqualified-id"
}
}
}
// I am honestly not sure what to do with this funciton or what should be included in it's body
void Grid_Walk:: generate_random_walk(Grid_Walk walk)
{
int move;
int i,j,letters;
move = rand() % 4;
bool blocked = false;
while(!blocked){
for (letter = 1; letter < 26; letter++)
{
switch (move)
{
case 0:
if (can_move_up(i,j,walk))
{ //unoccupied position
++j; ++letters;
walk[i][j] ="A";
break;
}
else{
blocked = true;
break;
}
case 1:
if (can_move_down(i,j,walk))
{ //unoccupied position
j--; ++letters;
walk[i][j] ="B";
break;
}
else{
blocked = true;
break;
}
case 2:
if (can_move_left(i,j,walk))
{ //unoccupied position
i--; ++letters;
walk[i][j] ="C";
break;
}
else{
blocked = true;
break;
}
case 3:
if (can_move_right(i,j,walk))
{ //unoccupied position
i++; ++letters;
walk[i][j] ="D";
break;
}
else{
blocked = true;
break;
} default: break;
}//close switch
}
}
if (blocked)
break;
}
// Will print the random walk to the grid
void Grid_Walk::print_array(Grid_Walk walk)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
cout << walk[i][j]; // Xcode error "Unexpected type name 'Grid'"
}
cout << endl;
}
}
bool Grid_Walk::can_move_up(int i, int j, Grid_Walk walk)
{
if (i > 0 && walk[i - 1][j] == DOT)
{
return true;
}
else
{
return false;
}
}
bool Grid_Walk:: can_move_down(int i, int j, Grid_Walk walk)
{
if (i < 9 && walk[i + 1][j] == DOT)
{
return true;
}
else
{
return false;
}
}
bool Grid_Walk:: can_move_left(int i, int j, Grid_Walk walk)
{
if (j > 0 && walk[i][j - 1] == DOT)
{
return true;
}
else
{
return false;
}
}
bool Grid_Walk:: can_move_right(int i, int j, Grid_Walk walk)
{
if (j < 9 && walk[i][j + 1] == DOT)
{
return true;
}
else
{
return false;
}
}
int main(void)
{
const int SIZE = 10;
char walk[SIZE][SIZE]; //array variable
char flag = 'A'; //flag for visited position; initially set to A
int i, j; //counter variables for loops
int rand_num; //variable for temporary storage of random numbers
int cycle_counter = 0; //count cycles through while loop
for(i = 0; i < SIZE; i++)
{//initiating array
for(j = 0; j < SIZE; j++) //elements
{
walk[i][j] = DOT;
}
}
DOT i = 5; j = 5; //initial position in array
srand((unsigned) time(0)); //create seed for function rand(), based on CPU time
while(flag <= 'Z')
{
rand_num = rand() % 4; //random number in current cycle
if( (rand_num == UP) && (i > 0) && (walk[i - 1][j] == DOT) )
{
//rand_num == UP - tells which direction!
//i > 0 - tests for up array bound
//walk[i - 1][j] == DOT will test if there is a dot up from current position
walk[--i][j] = flag; //--i = move to the up from current position
flag++; //C treats integers and chars the same (0-255, ASCII...)!
}
else if( (rand_num == DOWN) && (i < SIZE - 1) && (walk[i + 1][j] == DOT) )
{
//rand_num == DOWN - tells which direction!
//i < SIZE - 1 - tests for down array bound (C counts from zero!)
//walk[i + 1][j] == DOT- test if there is a dot down from current position
walk[++i][j] = flag; //++i = move to the down from current position flag++;
//C treats integers and chars the same (0-255, ASCII...)!
}
else if( (rand_num == LEFT) && (j > 0) && (walk[i][j - 1] == DOT) )
{
//rand_num == LEFT - tells which direction!
//j > 0 - test for left array bound (C counts from zero!)
//walk[i][j - 1] == DOT - tests if there is a dot left from current position
walk[i][--j] = flag; //--j = move to the left from current position flag++;
//C treats integers and chars the same (0-255, ASCII...)!
}
else if( (rand_num == RIGHT) && (j < SIZE - 1) && (walk[i][j + 1] == DOT) )
{
//rand_num == RIGHT - tells which direction!
//j < SIZE - 1- test for right array bound (C counts from zero!)
//walk[i][j + 1] == DOT - tests if there is a dot right from current position
walk[i][++j] = flag; //++j = move to the right from current position flag++;
//C treats integers and chars the same (0-255, ASCII...)!
}
else
//in every other case continue;
//loop goes on the next cycle
}
//following loops print results
for(i = 0; i < SIZE; i++)
{
//these two loops
for(j = 0; j < SIZE; j++)
//access all array elements
printf("%ct", walk[i][j]);
//print current element on screen putchar(' ');
//make a new line
}
return 0;
}

More Related Content

Similar to Write a C++ program which generates and displays a random walk acros.pdf

i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docx
ursabrooks36447
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8alish sha
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8alish sha
 
Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
Durgadevi palani
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
NiravPanchal50
 
Print Star pattern in java and print triangle of stars in java
Print Star pattern in java and print triangle of stars in javaPrint Star pattern in java and print triangle of stars in java
Print Star pattern in java and print triangle of stars in java
Hiraniahmad
 
Im trying again -Okay, Im in need of some help - this is the c.pdf
Im trying again -Okay, Im in need of some help - this is the c.pdfIm trying again -Okay, Im in need of some help - this is the c.pdf
Im trying again -Okay, Im in need of some help - this is the c.pdf
eyeonsecuritysystems
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q LPerconaPerformance
 
Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02
Md. Ashikur Rahman
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
PiersRCoThomsonw
 
Weekly Report 5 7
Weekly Report 5 7Weekly Report 5 7
Weekly Report 5 7mimi
 
Weekly Report 5 7
Weekly Report 5 7Weekly Report 5 7
Weekly Report 5 7mimi
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
MomenMostafa
 
#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx
ajoy21
 
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
implement the following funtions. myg1 and myg2 are seperate. x and .pdfimplement the following funtions. myg1 and myg2 are seperate. x and .pdf
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
forladies
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
Bharat Kalia
 
Cbasic
CbasicCbasic
Cbasic
rohitladdu
 

Similar to Write a C++ program which generates and displays a random walk acros.pdf (20)

i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docx
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
 
Print Star pattern in java and print triangle of stars in java
Print Star pattern in java and print triangle of stars in javaPrint Star pattern in java and print triangle of stars in java
Print Star pattern in java and print triangle of stars in java
 
Im trying again -Okay, Im in need of some help - this is the c.pdf
Im trying again -Okay, Im in need of some help - this is the c.pdfIm trying again -Okay, Im in need of some help - this is the c.pdf
Im trying again -Okay, Im in need of some help - this is the c.pdf
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q L
 
Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
 
Weekly Report 5 7
Weekly Report 5 7Weekly Report 5 7
Weekly Report 5 7
 
Weekly Report 5 7
Weekly Report 5 7Weekly Report 5 7
Weekly Report 5 7
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
05 operators
05   operators05   operators
05 operators
 
#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx
 
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
implement the following funtions. myg1 and myg2 are seperate. x and .pdfimplement the following funtions. myg1 and myg2 are seperate. x and .pdf
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Cbasic
CbasicCbasic
Cbasic
 

More from mckenziecast21211

In a comparison of ectotherms and endotherms, which of the following.pdf
In a comparison of ectotherms and endotherms, which of the following.pdfIn a comparison of ectotherms and endotherms, which of the following.pdf
In a comparison of ectotherms and endotherms, which of the following.pdf
mckenziecast21211
 
Implement Breadth-First Search with a QueueSolution Program .pdf
Implement Breadth-First Search with a QueueSolution Program .pdfImplement Breadth-First Search with a QueueSolution Program .pdf
Implement Breadth-First Search with a QueueSolution Program .pdf
mckenziecast21211
 
Immunology what are TdT and AID, and what are their roles in B c.pdf
Immunology what are TdT and AID, and what are their roles in B c.pdfImmunology what are TdT and AID, and what are their roles in B c.pdf
Immunology what are TdT and AID, and what are their roles in B c.pdf
mckenziecast21211
 
IDS in the Cloud Please respond to the following(a) Explain w.pdf
IDS in the Cloud Please respond to the following(a) Explain w.pdfIDS in the Cloud Please respond to the following(a) Explain w.pdf
IDS in the Cloud Please respond to the following(a) Explain w.pdf
mckenziecast21211
 
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdfGandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
mckenziecast21211
 
Explain exploratory factor analysis and give real life examplesS.pdf
Explain exploratory factor analysis and give real life examplesS.pdfExplain exploratory factor analysis and give real life examplesS.pdf
Explain exploratory factor analysis and give real life examplesS.pdf
mckenziecast21211
 
Drag the labels to the correct category to demonstrate your understan.pdf
Drag the labels to the correct category to demonstrate your understan.pdfDrag the labels to the correct category to demonstrate your understan.pdf
Drag the labels to the correct category to demonstrate your understan.pdf
mckenziecast21211
 
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdfDo you agree that the Berg Letter, research moratorium, and Asilomar.pdf
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
mckenziecast21211
 
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdfBrief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
mckenziecast21211
 
A population has two alleles for a particular gene, A and a, and is .pdf
A population has two alleles for a particular gene, A and a, and is .pdfA population has two alleles for a particular gene, A and a, and is .pdf
A population has two alleles for a particular gene, A and a, and is .pdf
mckenziecast21211
 
A 12-year-old male complained of strange odors before loss of consci.pdf
A 12-year-old male complained of strange odors before loss of consci.pdfA 12-year-old male complained of strange odors before loss of consci.pdf
A 12-year-old male complained of strange odors before loss of consci.pdf
mckenziecast21211
 
2.Which of the following statements about evolution is falseNonrand.pdf
2.Which of the following statements about evolution is falseNonrand.pdf2.Which of the following statements about evolution is falseNonrand.pdf
2.Which of the following statements about evolution is falseNonrand.pdf
mckenziecast21211
 
can someone explain in a easy way chromosome walking I know its w.pdf
can someone explain in a easy way chromosome walking I know its w.pdfcan someone explain in a easy way chromosome walking I know its w.pdf
can someone explain in a easy way chromosome walking I know its w.pdf
mckenziecast21211
 
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
mckenziecast21211
 
Write an informal negation for each of the following statements. Be .pdf
Write an informal negation for each of the following statements. Be .pdfWrite an informal negation for each of the following statements. Be .pdf
Write an informal negation for each of the following statements. Be .pdf
mckenziecast21211
 
true or false1- The grouped frequency table should ideally have.pdf
true or false1- The grouped frequency table should ideally have.pdftrue or false1- The grouped frequency table should ideally have.pdf
true or false1- The grouped frequency table should ideally have.pdf
mckenziecast21211
 
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
Answer the questions that follow the VHDL code given below.  LIBRARY .pdfAnswer the questions that follow the VHDL code given below.  LIBRARY .pdf
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
mckenziecast21211
 
The weak D phenotype is thought to arise from several mechanisms. .pdf
The weak D phenotype is thought to arise from several mechanisms. .pdfThe weak D phenotype is thought to arise from several mechanisms. .pdf
The weak D phenotype is thought to arise from several mechanisms. .pdf
mckenziecast21211
 
The coding region of a BACTERIAL gene has the following sequence A.pdf
The coding region of a BACTERIAL gene has the following sequence A.pdfThe coding region of a BACTERIAL gene has the following sequence A.pdf
The coding region of a BACTERIAL gene has the following sequence A.pdf
mckenziecast21211
 
Regarding the ABO blood group system in humans, if an individual is g.pdf
Regarding the ABO blood group system in humans, if an individual is g.pdfRegarding the ABO blood group system in humans, if an individual is g.pdf
Regarding the ABO blood group system in humans, if an individual is g.pdf
mckenziecast21211
 

More from mckenziecast21211 (20)

In a comparison of ectotherms and endotherms, which of the following.pdf
In a comparison of ectotherms and endotherms, which of the following.pdfIn a comparison of ectotherms and endotherms, which of the following.pdf
In a comparison of ectotherms and endotherms, which of the following.pdf
 
Implement Breadth-First Search with a QueueSolution Program .pdf
Implement Breadth-First Search with a QueueSolution Program .pdfImplement Breadth-First Search with a QueueSolution Program .pdf
Implement Breadth-First Search with a QueueSolution Program .pdf
 
Immunology what are TdT and AID, and what are their roles in B c.pdf
Immunology what are TdT and AID, and what are their roles in B c.pdfImmunology what are TdT and AID, and what are their roles in B c.pdf
Immunology what are TdT and AID, and what are their roles in B c.pdf
 
IDS in the Cloud Please respond to the following(a) Explain w.pdf
IDS in the Cloud Please respond to the following(a) Explain w.pdfIDS in the Cloud Please respond to the following(a) Explain w.pdf
IDS in the Cloud Please respond to the following(a) Explain w.pdf
 
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdfGandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
Gandalf the Grey started in the Forest of Mirkwood at a point with co.pdf
 
Explain exploratory factor analysis and give real life examplesS.pdf
Explain exploratory factor analysis and give real life examplesS.pdfExplain exploratory factor analysis and give real life examplesS.pdf
Explain exploratory factor analysis and give real life examplesS.pdf
 
Drag the labels to the correct category to demonstrate your understan.pdf
Drag the labels to the correct category to demonstrate your understan.pdfDrag the labels to the correct category to demonstrate your understan.pdf
Drag the labels to the correct category to demonstrate your understan.pdf
 
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdfDo you agree that the Berg Letter, research moratorium, and Asilomar.pdf
Do you agree that the Berg Letter, research moratorium, and Asilomar.pdf
 
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdfBrief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
Brief Concepts and Questions EXAM 2 Chapter 8 DNA RNA Protein What i.pdf
 
A population has two alleles for a particular gene, A and a, and is .pdf
A population has two alleles for a particular gene, A and a, and is .pdfA population has two alleles for a particular gene, A and a, and is .pdf
A population has two alleles for a particular gene, A and a, and is .pdf
 
A 12-year-old male complained of strange odors before loss of consci.pdf
A 12-year-old male complained of strange odors before loss of consci.pdfA 12-year-old male complained of strange odors before loss of consci.pdf
A 12-year-old male complained of strange odors before loss of consci.pdf
 
2.Which of the following statements about evolution is falseNonrand.pdf
2.Which of the following statements about evolution is falseNonrand.pdf2.Which of the following statements about evolution is falseNonrand.pdf
2.Which of the following statements about evolution is falseNonrand.pdf
 
can someone explain in a easy way chromosome walking I know its w.pdf
can someone explain in a easy way chromosome walking I know its w.pdfcan someone explain in a easy way chromosome walking I know its w.pdf
can someone explain in a easy way chromosome walking I know its w.pdf
 
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
9. When a bacteriophage inserts its DNA into a bacterial chromosome,.pdf
 
Write an informal negation for each of the following statements. Be .pdf
Write an informal negation for each of the following statements. Be .pdfWrite an informal negation for each of the following statements. Be .pdf
Write an informal negation for each of the following statements. Be .pdf
 
true or false1- The grouped frequency table should ideally have.pdf
true or false1- The grouped frequency table should ideally have.pdftrue or false1- The grouped frequency table should ideally have.pdf
true or false1- The grouped frequency table should ideally have.pdf
 
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
Answer the questions that follow the VHDL code given below.  LIBRARY .pdfAnswer the questions that follow the VHDL code given below.  LIBRARY .pdf
Answer the questions that follow the VHDL code given below. LIBRARY .pdf
 
The weak D phenotype is thought to arise from several mechanisms. .pdf
The weak D phenotype is thought to arise from several mechanisms. .pdfThe weak D phenotype is thought to arise from several mechanisms. .pdf
The weak D phenotype is thought to arise from several mechanisms. .pdf
 
The coding region of a BACTERIAL gene has the following sequence A.pdf
The coding region of a BACTERIAL gene has the following sequence A.pdfThe coding region of a BACTERIAL gene has the following sequence A.pdf
The coding region of a BACTERIAL gene has the following sequence A.pdf
 
Regarding the ABO blood group system in humans, if an individual is g.pdf
Regarding the ABO blood group system in humans, if an individual is g.pdfRegarding the ABO blood group system in humans, if an individual is g.pdf
Regarding the ABO blood group system in humans, if an individual is g.pdf
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 

Write a C++ program which generates and displays a random walk acros.pdf

  • 1. Write a C++ program which generates and displays a random walk across a grid. A 2- dimensional array of characters will be used for this grid. The cells visited by the walk will be labeled by capital letters with A being the first cell, B the cell moved to from A, and so on, ending either when Z is reached or when it is not possible to move to another cell. The following libraries, constant definition, and type definition are needed in the program: #include #include // for srand and rand #include // for time using namespace std; const int SIZE = 10; typedef char Grid[SIZE][SIZE] The grid must be set to have all its elements be the character ’.’ before the walk is begun. The program must contain the following function prototypes, the main function, and the function definitions for all the other functions: // Function prototypes bool can_move_up(int i, int j, Grid walk); bool can_move_down(int i, int j, Grid walk); bool can_move_left(int i, int j, Grid walk); bool can_move_right(int i, int j, Grid walk); void init_array(Grid walk); void generate_random_walk(Grid walk); void print_array(Grid walk); int main(void) { Grid walk; // the grid in which the random walk occurs srand((unsigned) time(NULL)); init_array(walk); generate_random_walk(walk); print_array(walk); return 0; } The four functions can_move _* must return whether or not it is possible to move in the particular direction in the grid. For example, a function call like if (can_move_up(i, j, walk)) could be used to determine whether or not it is possible to move up. The rule for a move being possible is that if it doesn’t go outside of the grid and isn’t already part of the walk, then that
  • 2. move is possible. The function init_array must set all characters in the grid to ’.’ The function generate_random_walk must modify the cells of grid by changing ones that are part of the walk to letters. The function print_array must print the resulting grid in the form shown in the sample run below. In the function generate_random_walk, at each step of the walk, randomly select one of the 4 directions and try to move in that direction. If that move isn’t available, try the other moves in turn until one is possible. If all 4 directions are blocked, the walk must terminate, and the program must continue and print out the walk. To select one of the 4 directions randomly, use the expression: rand() % 4 The function rand returns an integer, and finding the remainder of this integer divided by 4 results in getting one of the numbers 0, 1, 2, or 3. Use these 4 numbers to represent the 4 directions up, down, left and right. The call to the function srand from the main function seeds the pseudo-random number generator used by rand so that different sequences of numbers will be generated by calls to rand each time the program is run. Solution #include //input output functions in C++ #include //rand() and srand() functions #include //time() function for creating seed #include #include // for srand and rand #include // for time using namespace std; class Grid_Walk { const int SIZE = 10; #define UP 0 //flag for up #define DOWN 1 //flag for down #define LEFT 2 //flag for left #define RIGHT 3 //flag for right #define DOT '.'//flag for dot public: void init_array(Grid_Walk walk);
  • 3. void generate_random_walk(Grid_Walk walk); void print_array(Grid_Walk walk); bool can_move_up(int i, int j, Grid_Walk walk); bool can_move_down(int i, int j, Grid_Walk walk); bool can_move_left(int i, int j, Grid_Walk walk); bool can_move_right(int i, int j, Grid_Walk walk); }; //Member function definitions void Grid_Walk:: init_array(Grid_Walk walk) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { walk[i][j] = DOT; // Xcode gives me error for '=' "Expected unqualified-id" walk[0][0] = 'A'; // Xcode gives me error for '=' "Expected unqualified-id" } } } // I am honestly not sure what to do with this funciton or what should be included in it's body void Grid_Walk:: generate_random_walk(Grid_Walk walk) { int move; int i,j,letters; move = rand() % 4; bool blocked = false; while(!blocked){ for (letter = 1; letter < 26; letter++) { switch (move) { case 0: if (can_move_up(i,j,walk)) { //unoccupied position ++j; ++letters; walk[i][j] ="A";
  • 4. break; } else{ blocked = true; break; } case 1: if (can_move_down(i,j,walk)) { //unoccupied position j--; ++letters; walk[i][j] ="B"; break; } else{ blocked = true; break; } case 2: if (can_move_left(i,j,walk)) { //unoccupied position i--; ++letters; walk[i][j] ="C"; break; } else{ blocked = true; break;
  • 5. } case 3: if (can_move_right(i,j,walk)) { //unoccupied position i++; ++letters; walk[i][j] ="D"; break; } else{ blocked = true; break; } default: break; }//close switch } } if (blocked) break; } // Will print the random walk to the grid void Grid_Walk::print_array(Grid_Walk walk) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { cout << walk[i][j]; // Xcode error "Unexpected type name 'Grid'" } cout << endl; } } bool Grid_Walk::can_move_up(int i, int j, Grid_Walk walk) {
  • 6. if (i > 0 && walk[i - 1][j] == DOT) { return true; } else { return false; } } bool Grid_Walk:: can_move_down(int i, int j, Grid_Walk walk) { if (i < 9 && walk[i + 1][j] == DOT) { return true; } else { return false; } } bool Grid_Walk:: can_move_left(int i, int j, Grid_Walk walk) { if (j > 0 && walk[i][j - 1] == DOT) { return true; } else { return false; } } bool Grid_Walk:: can_move_right(int i, int j, Grid_Walk walk) { if (j < 9 && walk[i][j + 1] == DOT) { return true;
  • 7. } else { return false; } } int main(void) { const int SIZE = 10; char walk[SIZE][SIZE]; //array variable char flag = 'A'; //flag for visited position; initially set to A int i, j; //counter variables for loops int rand_num; //variable for temporary storage of random numbers int cycle_counter = 0; //count cycles through while loop for(i = 0; i < SIZE; i++) {//initiating array for(j = 0; j < SIZE; j++) //elements { walk[i][j] = DOT; } } DOT i = 5; j = 5; //initial position in array srand((unsigned) time(0)); //create seed for function rand(), based on CPU time while(flag <= 'Z') { rand_num = rand() % 4; //random number in current cycle if( (rand_num == UP) && (i > 0) && (walk[i - 1][j] == DOT) ) { //rand_num == UP - tells which direction! //i > 0 - tests for up array bound //walk[i - 1][j] == DOT will test if there is a dot up from current position walk[--i][j] = flag; //--i = move to the up from current position flag++; //C treats integers and chars the same (0-255, ASCII...)! } else if( (rand_num == DOWN) && (i < SIZE - 1) && (walk[i + 1][j] == DOT) )
  • 8. { //rand_num == DOWN - tells which direction! //i < SIZE - 1 - tests for down array bound (C counts from zero!) //walk[i + 1][j] == DOT- test if there is a dot down from current position walk[++i][j] = flag; //++i = move to the down from current position flag++; //C treats integers and chars the same (0-255, ASCII...)! } else if( (rand_num == LEFT) && (j > 0) && (walk[i][j - 1] == DOT) ) { //rand_num == LEFT - tells which direction! //j > 0 - test for left array bound (C counts from zero!) //walk[i][j - 1] == DOT - tests if there is a dot left from current position walk[i][--j] = flag; //--j = move to the left from current position flag++; //C treats integers and chars the same (0-255, ASCII...)! } else if( (rand_num == RIGHT) && (j < SIZE - 1) && (walk[i][j + 1] == DOT) ) { //rand_num == RIGHT - tells which direction! //j < SIZE - 1- test for right array bound (C counts from zero!) //walk[i][j + 1] == DOT - tests if there is a dot right from current position walk[i][++j] = flag; //++j = move to the right from current position flag++; //C treats integers and chars the same (0-255, ASCII...)! } else //in every other case continue; //loop goes on the next cycle } //following loops print results for(i = 0; i < SIZE; i++) { //these two loops for(j = 0; j < SIZE; j++) //access all array elements
  • 9. printf("%ct", walk[i][j]); //print current element on screen putchar(' '); //make a new line } return 0; }