SlideShare a Scribd company logo
1 of 9
Download to read offline
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 .docxursabrooks36447
 
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
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfNiravPanchal50
 
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 javaHiraniahmad
 
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.pdfeyeonsecuritysystems
 
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 part02Md. 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).docxPiersRCoThomsonw
 
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.pdfanjandavid
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statementsMomenMostafa
 
#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.docxajoy21
 
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 .pdfforladies
 
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.pdfRahul04August
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 

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
 
Cbasic
CbasicCbasic
Cbasic
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 

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.pdfmckenziecast21211
 
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 .pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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 .pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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,.pdfmckenziecast21211
 
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 .pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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 .pdfmckenziecast21211
 
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. .pdfmckenziecast21211
 
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.pdfmckenziecast21211
 
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.pdfmckenziecast21211
 

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

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

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; }