How to assign 2D array with random numbers
Aug 6, 2022 at 2:14am UTC
How do I assign 2D array with random numbers. I need to display this
C1 C2 C3 C4 C5
R1 2 3 4 1 6
R2 3 3 4 4 5
R3 4 5 3 6 8
R4 5 7 6 8 4
Please help fast.
Aug 6, 2022 at 2:31am UTC
loop over it and assign.
see the reference pages here on <random> for examples of using that.
you can flatten a 2d array to 1d for stuff like this.
int x[10][10];
for(int i = 0; i < 100; i++) //100 is 10x10 rows *cols ..
x[i] = random value
Aug 6, 2022 at 8:51am 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
#include <iostream>
#include <random>
#include <utility>
#include <array>
constexpr size_t COLS { 5 }, ROWS { 4 };
constexpr std::pair range { 1, 9 };
std::mt19937 rng(std::random_device {}());
int main() {
std::uniform_int_distribution distrib(range.first, range.second);
std::array<std::array<int , COLS>, ROWS> nums;
for (auto & r : nums)
for (auto & c : r)
c = distrib(rng);
for (const auto & r : nums) {
for (const auto & c : r)
std::cout << c << ' ' ;
std::cout << '\n' ;
}
}
4 7 5 2 5
3 6 5 5 6
4 2 9 7 6
9 1 2 1 9
You'll need to add the labels if required.
Topic archived. No new replies allowed.