我想创建一个 martix 9x9,里面有 10 个,用 C/C++ 随机填充
例如它应该看起来像这样:
array[[ 0, 1, 0, 0, 0, 1, 0, 0, 0, ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, ]
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, ]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, ]
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, ]
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, ]
[ 1, 0, 0, 0, 0, 1, 0, 0, 0, ]]
有不同的方法。您可以用
1
填充前 10 个位置,然后调用 std::shuffle
将它们放在随机位置。您还可以创建一个可用职位列表,然后从该列表中随机选择 10 个。
后者的注释示例:
#include <array> // array
#include <iostream> //
#include <numeric> // iota
#include <random> // mt19937, uniform_int_distribution
int main() {
constexpr unsigned side_size = 9;
// a seeded pseudo number generator
std::mt19937 prng(std::random_device{}());
// all zeroes:
std::array<std::array<int, side_size>, side_size> arr_to_fill{};
// create an array with all available positions number from 0-
std::array<unsigned, side_size * side_size> positions;
std::iota(positions.begin(), positions.end(),
0); // [0, side_size*side_size)
unsigned ones = 10; // the number of 1's we want
for (unsigned i = 0; i < ones; ++i) {
unsigned last = positions.size() - 1 - i; // last unpicked pos
// distribution of random numbers from 0 to last (inclusive)
std::uniform_int_distribution dist(0u, last);
unsigned idx = dist(prng); // get random index ...
unsigned pos = positions[idx]; // ... to pick a position
positions[idx] = positions[last]; // copy last unpicked position
// put a 1 in the chosen positions place:
arr_to_fill[pos / side_size][pos % side_size] = 1;
}
// print result:
for (auto& inner : arr_to_fill) {
for (auto v : inner) std::cout << ' ' << v;
std::cout << '\n';
}
}