Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c++ - How can I code a two-dimensional array of 50 rows and 50 columns into a function which randomly assigns an asterisk to an element?

I have an assignment for a CS class where I'm learning C++. For this assignment, I have to write a two dimensional character array which can be passed to a function. The array has to consist of 50 rows and 50 columns. All elements must be initialized to a space (' ').

I have creating the array here I have also written a for loop to place the array in a grid. Now, I have to assign asterisks randomly to elements of the array, which are still left blank, and I cannot figure out how to do so.

#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>

using namespace std;

int main()
{
    const int rows = 50; // Variables
    const int col = 50;
    const char SIZE = ' ';
    const int hgt = 48;
    int X = rand() % 50; // *Edited: This code was copied from an older save
    int y = rand() % 50;

    char board[rows][col]; // Array initialization
    int i;
    int j;
    int x;

    srand((unsigned)time(0));  
    for (i = 0; i < rows; i++) // For loop to place array in grid.
    {
        for (j = 0; j < col; j++)
        {
            board[i][j] = SIZE;
        }
            board[x][y] = '*'
   }

    cout << setfill('-') << setw(50) << "" << endl; // Grid
    for (X = 0; X < hgt; X++)
    {
        cout << "|" << setfill(' ') << setw(49) << "|" << endl;
    }
    cout << setfill('-') << setw(50) << "" << endl;

        cin.ignore();
    cout << "Press Enter to continue..." << endl;
    cin.ignore();
    return 0;
}

The array works, the grid works. I just cannot figure out how to assign asterisks randomly placed in the grid and how to pass that array into a function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Concerning

how to pass that array into a function

An array is a special case concerning function parameters:

void f(int a[10]);

isn't a function with a value parameter of int[10] as it looks like. Arrays are not passed by value – they decay to a pointer to first element. Hence, the above function declaration is the same as

void g(int *a); // the same as g(int a[]);

If the array is a 2d array (an array of arrays), this doesn't change:

void f(int a[10][3]);

is the same as:

void g(int (*a)[3]); // the same as g(int a[][3]);

The mix of pointer and dimension makes things a bit complicated: The parentheses around *a are absolutely necessary because

void h(int *a[3]); // the same as void h(int *a[]); or void h(int **a);

would have a pointer to pointer(s) as argument what is something completely different.

However, there is a very simple trick to come around all theses issues:

Using a typedef:

typedef char Board[10][3];

or using using (more modern):

using Board = char[10][3];

Now, things become very easy:

void f(Board &board); // passing array by reference

which could be also written as:

void f(char (&board)[10][3]);

but the latter might look a bit scaring.

Btw. passing the array by reference prevents that the array type decays to a pointer type like demonstrated in the following small sample:

#include <iostream>

void f(char a[20])
{
  std::cout << "sizeof a in f(): " << sizeof a << '
';
  std::cout << "sizeof a == sizeof(char*)? "
    << (sizeof a == sizeof(char*) ? "yes" : "no")
    << '
';
}

void g(char (&a)[20])
{
  std::cout << "sizeof a in g(): " << sizeof a << '
';
}

int main()
{
  char a[20];
  std::cout << "sizeof a in main(): " << sizeof a << '
';
  f(a);
  g(a);
}

Output:

sizeof a in main(): 20
sizeof a in f(): 8
sizeof a == sizeof(char*)? yes
sizeof a in g(): 20

Live Demo on coliru


Concerning

I just cannot figure out how to assign asterisks randomly placed in the grid

I cannot say it shorter than molbdilno:

You need to do it repeatedly.


For a demonstration, I re-designed OPs code a bit:

#include <iomanip>
#include <iostream>

const int Rows = 10; //50;
const int Cols = 10; //50;

// for convenience
//typedef char Board[Rows][Cols];
using Board = char[Rows][Cols];

void fillGrid(Board &board, char c)
{
  for (int y = 0; y < Rows; ++y) {
    for (int x = 0; x < Cols; ++x) board[y][x] = c;
  }
}

void populateGrid(Board &board, int n, char c)
{
  while (n) {
    const int x = rand() % Cols;
    const int y = rand() % Rows;
    if (board[y][x] == c) continue; // accidental duplicate
    board[y][x] = c;
    --n;
  }
}

void printGrid(const Board &board)
{
  std::cout << '+' << std::setfill('-') << std::setw(Cols) << "" << "+
";
  for (int y = 0; y < Rows; ++y) {
    std::cout << '|';
    for (int x = 0; x < Cols; ++x) std::cout << board[y][x];
    std::cout << "|
";
  }
  std::cout << '+' << std::setfill('-') << std::setw(Cols) << "" << "+
";
}

int main()
{
  srand((unsigned)time(0));
  Board board;
  fillGrid(board, ' ');
  std::cout << "Clean grid:
";
  printGrid(board);
  std::cout << '
';
  populateGrid(board, 10, '*');
  std::cout << "Initialized grid:
";
  printGrid(board);
  std::cout << '
';
}

Output:

Clean grid:
+----------+
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

Initialized grid:
+----------+
|          |
|      *   |
|**  * *   |
|     *    |
|          |
|          |
|*         |
|          |
|    *     |
|   * *    |
+----------+

Live Demo on coliru


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...