Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

How to generate N random 1s in a zero-based matrix with C++

1 Answer

0 votes
#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 

*/

 



answered 6 days ago by avibootz
edited 6 days ago by avibootz
...