Question

Write a C++ program to simulate a stream path. In this problem you can make the...

Write a C++ program to simulate a stream path.

In this problem you can make the following assumptions

1. The elevation grid will be a n row, m column grid of integers, where n and m are constant.

2. Once the stream origin location is specified, then the stream flows to whichever of the four adjacent locations in the grid represents the largest descent.

3. If more than one of the adjacent locations have the largest descent, then the water flows to whichever adjacent location appears first in the last item's list.

4. The process continues, with the stream flowing from location to location until it either reachers a location where none of the four adjacent locations has its elevation strictly less than that location, or until it reachesr the edge of the grid. (any row with index 0 or n-1 or any column with index 0 or n-1).

Write a C++ program that sets up a grid, and asks the user to input an initial location. If the input location is an invalid location, the program should print "Invalid location" to the screen. Otherwise the program should call a function:

bool moveToLowerElev(int elev[][m], int n, int m, int& r, int& c)

Given the row and column of the input location, this function should first check to see if that location is on the end of the grid. If it is, the function should return false. If it is not, the function should check the four adjacent locations. If none has an elevation strictly less than the current location, then the function should return false. Otherwise the function should return true, and return the row and column of the adjacent location with the leaset elevation through the reference parameters int& r and int& c.

If moveToLowerElev returns false, the main program should output "Path ends." Otherwise the program should print the new row and colum, as well as the elevation of the new location.

Use the grid int elev[n][m] = {0, 0, 0, 0, 0}

{0, 1, 2, 3, 4}

{0, 2, 0, 2, 0}

{2, 3, 1, 2, 4}

{3, 4, 3, 4, 5}

{4, 5, 5, 2, 6}

{3, 3, 3, 2, 1}

Here is an example of the program

Input the origin location (row and column): 4 3

Row 3, column 3, elevation 2

The moveToLowerElev should be defined after the main function.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

// function to find the min of two elements
int min(int a, int b) {
    return a>b?b:a;
}

bool moveToLowerElev(int **elev, int n, int m, int& r,int& c) {

    if(r < 0 || r >= n || c < 0 || c>= m) { // if the data is invalid
           cout<<"Invalid row or column"<<endl;
           return false;
    }
    if(r == 0 || r == n-1 || c == 0 || c == m-1) {// if we are at any border side
        cout<<"PathEnds."<<endl;
        return true; // we havefind the path, and it is at the end
    }
    // find the min elevation we would like togo
    int min_elev = min(elev[r-1][c],min(elev[r][c+1], min(elev[r+1][c], elev[r][c-1])));

    // if the min elevation is greater than thecurrent elevation
    if(elev[r][c] < min_elev) { // there is no,way to go
        cout<<"PathEnds."<<endl;
        return false; // returnfalse, as we can not find a way
    }

    if(min_elev == elev[r-1][c]) { // if the minelevation is the top, goto top
        cout<<"Row"<<(r-1)<<", column "<<(c)<<", elevation"<<elev[r-1][c]<<endl;
        returnmoveToLowerElev(elev, n, m, --r, c);
    } else if(min_elev == elev[r][c+1]) {// if themin elevation is the right, goto right
        cout<<"Row"<<(r)<<", column "<<(c+1)<<", elevation"<<elev[r][c+1]<<endl;
        returnmoveToLowerElev(elev, n, m, r, ++c);
    } else if(min_elev == elev[r+1][c]) { // if themin elevation is the bottom, goto bottom
        cout<<"Row"<<(r+1)<<", column "<<(c)<<", elevation"<<elev[r+1][c]<<endl;
        returnmoveToLowerElev(elev, n, m, ++r, c);
    } else { // if the min elevation is the left,goto left
        cout<<"Row"<<(r)<<", column "<<(c-1)<<", elevation"<<elev[r][c-1]<<endl;
        returnmoveToLowerElev(elev, n, m, r, --c);
    }
}

// function to read the data from a gove file
int** read(string filename, int& N, int &M) {
    ifstream in(filename.c_str()); // open the fileto read
    if(!in) { // if the file is not opened
        cout<<"FILE NOTFOUND"<<endl;
        exit(0);
    }

    int r, c;
    in>>r>>c; // read the dimensions ofthe grind first

    //cout<<"File contents are :"<<endl;
    //cout<<r<<""<<c<<endl;
    // create a grid
    int** grid = new int*[r];
    for(int i = 0; i < r; i++) {
        grid[i] = newint[c];
    }
    for(int i = 0; i < r; i++) {
        for(int j = 0; j < c;j++) {
           in>>grid[i][j];
           //cout<<grid[i][j]<<" ";
        }
       //cout<<endl;
    }
    N = r;
    M = c;
    in.close(); // close the file
    return grid; // return the grid
}

int main() {
string filename;
    cout<<"Enter the file name : ";
    cin >> filename;

    int N, M; // dimensions of the grid
    int** elev = read(filename, N, M);

    char ch = 'y';
    do {
        cout<<"Input theorigin location (row and column): ";
        int i, j;
        cin>> i>>j;// read the location from the user

        // find thepath
        moveToLowerElev(elev, N,M, i, j);

        // ask if he wants tocontinue
        cout<<"Enteranother origin location (y/n)? ";
        cin >> ch;

    } while(ch == 'y'); // while the user enters'y' continue the loop
return 0;
}


// OUTPUT

Enter the file name : grid.txt Input the origin location (row and column) 0 10 Inva lid row or column Enter another origin location (y/n)? Input the origin location (row and column): 0 2 Path Ends. Enter another origin location (y/n)? Input the origin location (row and column): 4 3 Row 3, column 3, elevation 2 Row 3, column 2, elevation 1 Row 2, column 2, elevation 0 Path Ends. Enter another origin location (y/n)? Input the origin location (row and column): 1 3 Row 0, column 3, elevation 0 Path Ends. Enter another origin location (y/n)? n Process returned 0 (0x0) execution time: 32.084s Press any key to continue.

Add a comment
Know the answer?
Add Answer to:
Write a C++ program to simulate a stream path. In this problem you can make the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths...

    JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths possible in this maze. The program uses recursion. Can someone please explain to me why the program will pick one path if multiple traversable paths are available? Why does the program choose one path over a different path? (I believe it has something to do with the recursion terminating when a solution is found but I'm not sure.) Thank you!!!! The codes: public class...

  • Please use Python 3, thank you~ Write a program that: Defines a function called find_item_in_grid, as...

    Please use Python 3, thank you~ Write a program that: Defines a function called find_item_in_grid, as described below. Calls the function find_item_in_grid and prints the result. The find_item_in_grid function should have one parameter, which it should assume is a list of lists (a 2D list). The function should ask the user for a row number and a column number. It should return (not print) the item in the 2D list at the row and column specified by the user. The...

  • I need help with the following and written in c++ thank you!: 1) replace the 2D...

    I need help with the following and written in c++ thank you!: 1) replace the 2D arrays with vectors 2) add a constructor to the Sudoku class that reads the initial configuration from a file 3) adds a function to the Sudoku class that writes the final Sudoku grid to a file or to the standard output device, cout. Sudoku.h #pragma once /* notes sudoku() default constructor precondition : none postcondition: grid is initialized to 0 sudoku(g[][9]) 1-parameter constructor precondition...

  • PLEASE COMPLETE IN C++ LANGUAGE Location row : int = -1 col : int = -1...

    PLEASE COMPLETE IN C++ LANGUAGE Location row : int = -1 col : int = -1 setLocation(row : int, col : int) getRow(): int getColl): int isEmpty(): bool Details Write all the code necessary to implement the Location class as shown in the UML Class Diagram to the right. Do this in a project named snake (we'll continue adding files to this project as the term progresses). Your class definition and implementation should be in separate files. When complete, you...

  • Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every...

    Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every part, and include java doc and comments Create a battleship program. Include Javadoc and comments. Grade 12 level coding style using java only. You will need to create a Ship class, Location class, Grid Class, Add a ship to the Grid, Create the Player class, the Battleship class, Add at least one extension. Make sure to include the testers. Starting code/ sample/methods will be...

  • Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three...

    Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three functionalities: Covert a binary string to corresponding positive integers Convert a positive integer to its binary representation Add two binary numbers, both numbers are represented as a string of 0s and 1s To reduce student work load, a start file CSCIProjOneHandout.cpp is given. In this file, the structure of the program has been established. The students only need to implement the...

  • Instructions Write a program in Java that implements the A* algorithm to find a path from...

    Instructions Write a program in Java that implements the A* algorithm to find a path from any two given nodes. Problem Overview & Algorithm Description In a fully-observable environment where there are both pathable and blocked nodes, an agent must find a good path from their starting node to the goal node. The agent must use the A* algorithm to determine its path. For this program, you must use the Manhattan method for calculating the heuristic. Remember: your heuristic function...

  • The following C++  code contains an incomplete program that should be able to calculate the distance between...

    The following C++  code contains an incomplete program that should be able to calculate the distance between a series of geocoded locations. Two parts of the program need to be completed: 1. The portion of the main() function that calculates the distances between each of the hard-coded 5 locations, and stores it in a two-dimensional array declared as distances. 2. A portion of the calculateDistanceBetweenLocations(l1, l2) function; omitted code spaces are designed with a // TODO: comment. The code is properly...

  • Having a rough time getting started with the constructors and the display function of this class,...

    Having a rough time getting started with the constructors and the display function of this class, any advice/assitance is appreciated! Task You will write a class called Grid, and test it with a couple of programs. A Grid object will be made up of a grid of positions, numbered with rows and columns. Row and column numbering start at 0, at the top left corner of the grid. A grid object also has a "mover", which can move around to...

  • Write a program that, given a starting location in a 2D grid of characters, will count...

    Write a program that, given a starting location in a 2D grid of characters, will count how many contiguously connected @ symbols there are. Cells have to be direct neighbors either horizontally or vertically to count as contiguous. However, the right/left and top/bottom edges ARE considered to be connected – you can “wrap around” from one side of the matrix to the opposite one. The grid of chars will always be 10x10. Your program should load the grid of chars...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT