Get random n rows from a 2D array in C++
This tutorial will show you how to get the random n number of rows from a 2D array in C++. The 2D array is nothing but a matrix which have rows and columns. We will generate n random numbers within the range of maximum and minimum number of rows to get any random number of rows.
Algorithm
Note: Refer to How to generate a random number in C++ module to get familiar with the rand()
function.
Step 1: Define the 2D array of any data type. Define the value of n i.e. the number of random rows you want to get. But n should be less than or equal to the actual number of rows present in the 2D array.
Step 2: Then call the srand(unsigned int seed)
to generate different random numbers at every execution.
Step 3: Run the loop n times. Then generate the random integer within the range of minimum and maximum number of rows. The formula to generate the random numbers within the range is (rand() % (max - min + 1))
+ min
Here the minimum range would be 0 because the array indexes start from 0 and the maximum would be the index of a maximum number of rows present in a 2D array.
Step 4: Then print that particular row element using a loop for column elements.
C++ code for getting random n rows from a 2D array in C++
code:
#include <iostream> #include <cstdlib> using namespace std; int main() { int arr[4][4] = {{1, 0, 3, 2}, {4, 5, 2, 3}, {5, 8, 9, 0}, {2, 6, 7, 4}}; int n = 3; srand(time(0)); for (int i = 0; i < n; i++) { int row = (rand() % 4); // (rand() % (3-0+1)) + 0 std::cout << "row : " <<row << std::endl; for (int j = 0; j < 4; j++) { cout << arr[row][j] << " "; } cout << endl; } return 0; }
Output :
row : 1 4 5 2 3 row : 3 2 6 7 4 row : 0 1 0 3 2
Leave a Reply