#include <iostream>
#include <vector>
#include <random>
#include <unordered_set>
/*
Generate N random 1s in a zero-based matrix.
The approach:
- Represent the matrix as a flat index space [0, rows*cols).
- Randomly pick unique positions using an unordered_set.
- Convert each chosen flat index back to (row, col).
- This avoids repeatedly sampling coordinates until finding an empty cell.
- The algorithm is efficient for sparse placement and easy to reason about.
*/
// Utility function: print the matrix
void print_matrix(const std::vector<std::vector<int>>& m) {
for (const auto& row : m) {
for (int v : row) {
std::cout << v << ' ';
}
std::cout << '\n';
}
}
// Generate N random 1s in a zero-based matrix
std::vector<std::vector<int>> generate_random_matrix(int rows, int cols, int count) {
// Create a matrix filled with zeros
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));
// Total number of cells
const int total = rows * cols;
// Guard: ensure count does not exceed available cells
if (count > total) {
throw std::runtime_error("Requested more 1s than available cells.");
}
// Random engine and distribution
std::random_device rd; // seeds from hardware
std::mt19937 gen(rd()); // fast, high-quality generator
std::uniform_int_distribution<int> dist(0, total - 1);
// Use a set to ensure unique positions
std::unordered_set<int> chosen;
chosen.reserve(count);
// Draw unique random positions
while (static_cast<int>(chosen.size()) < count) {
chosen.insert(dist(gen));
}
// Convert flat indices to (row, col) and mark them
for (int index : chosen) {
int r = index / cols;
int c = index % cols;
matrix[r][c] = 1;
}
return matrix;
}
int main() {
// Example parameters
int rows = 5;
int cols = 7;
int number_of_ones = 10;
// Generate the matrix
auto result = generate_random_matrix(rows, cols, number_of_ones);
print_matrix(result);
}
/*
run:
1 0 1 0 1 1 0
0 0 1 0 0 0 0
1 1 0 0 0 1 0
0 0 0 0 1 0 0
0 1 0 0 0 0 0
*/