New, Help.
Oct 11, 2018 at 11:39am UTC
Hi, I started learning from this book and I am trying to generate a random number from 1-100. The result is generated in a line and I am trying to make it in a 10x10 grid. It says use something like the GRID_SIZE method but im not quite sure on how to use it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void InitRand() {
srand((unsigned int )time(NULL));
}
int main()
{
InitRand();
const int GRID_SIZE = 10;
int grid[GRID_SIZE][GRID_SIZE];
int k = 0;
while (k++ < 100) {
int r = (rand() % 100) + 1;
cout << r << " " ;
}
system("pause" );
return 0;
}
Oct 11, 2018 at 12:12pm UTC
Normally you would have two nested loops when dealing with a grid.
One loop for the rows and one loop for the columns.
1 2 3 4 5
for (int row = 0; row < GRID_SIZE; row++)
for (int col = 0; col < GRID_SIZE; col++)
{
// use grid[row][col];
}
The 2d array is very common, so devote some time to it.
Oct 11, 2018 at 12:17pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void InitRand() {
srand((unsigned int )time(NULL));
}
int main()
{
InitRand();
const int GRID_SIZE = 10;
int grid[GRID_SIZE][GRID_SIZE];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j] = (rand() % 100) + 1;
cout << grid[i][j] << " " ;
if (j == 9) {
cout << endl;
}
}
}
system("pause" );
return 0;
}
Last edited on Oct 11, 2018 at 12:18pm UTC
Oct 11, 2018 at 1:19pm UTC
@Manga: What are these magick
10
on lines 16 and 17?
(The loop by Thomas is more expressive.)
You don't need any array (or even nested loop), if you simply want to show numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <iomanip>
#include <random>
#include <chrono>
int main()
{
unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 generator( seed1 ); // insufficient seed
std::uniform_int_distribution<int > distribution( 1, 100 );
constexpr int GRID_SIZE = 10;
for (int i=0; i < GRID_SIZE*GRID_SIZE; ++i ) {
int number = distribution(generator);
std::cout << std::setw(4) << number;
if ( i % GRID_SIZE + 1 == GRID_SIZE ) std::cout << '\n' ;
}
}
Oct 11, 2018 at 5:48pm UTC
OP has a 2d array. I thought the numbers should fit inside the array for safe keeping. As for the magick 10... That is just how I roll!
Ok I can't back that up. It was a result of me trying to type too fast. I wanted to finish and post before anyone else. But that Thomas is quick on the draw!
Topic archived. No new replies allowed.