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,844 questions

55,671 answers

573 users

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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*
    Generate N random 1s in a zero-based matrix.

    Strategy:
    - Treat the matrix as a flat index space [0, rows*cols).
    - Randomly pick unique positions by marking them in a temporary array.
    - Convert each chosen flat index back to (row, col).
    - This avoids repeatedly searching for empty cells and keeps the logic simple.
*/

// Print the matrix
void print_matrix(int **m, int rows, int cols) {
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            printf("%d ", m[r][c]);
        }
        printf("\n");
    }
}

// Allocate a rows×cols matrix initialized to zero
int **allocate_matrix(int rows, int cols) {
    int **m = malloc(rows * sizeof(int *));
    if (!m) {
        fprintf(stderr, "Allocation failed.\n");
        exit(EXIT_FAILURE);
    }

    for (int r = 0; r < rows; ++r) {
        m[r] = calloc(cols, sizeof(int));
        if (!m[r]) {
            fprintf(stderr, "Allocation failed.\n");
            exit(EXIT_FAILURE);
        }
    }

    return m;
}

// Free the matrix
void free_matrix(int **m, int rows) {
    for (int r = 0; r < rows; ++r) {
        free(m[r]);
    }

    free(m);
}

// Generate N random 1s in a zero-based matrix
int **generate_random_matrix(int rows, int cols, int count) {
    int total = rows * cols;

    if (count > total) {
        fprintf(stderr, "Requested more 1s than available cells.\n");
        exit(EXIT_FAILURE);
    }

    // Allocate the matrix
    int **matrix = allocate_matrix(rows, cols);

    // Temporary array to mark chosen positions
    int *chosen = calloc(total, sizeof(int));
    if (!chosen) {
        fprintf(stderr, "Allocation failed.\n");
        exit(EXIT_FAILURE);
    }

    // Seed the random generator
    srand((unsigned)time(NULL));

    // Draw unique positions
    int placed = 0;
    while (placed < count) {
        int index = rand() % total;
        if (!chosen[index]) {
            chosen[index] = 1;
            placed++;
        }
    }

    // Convert flat indices to (row, col)
    for (int i = 0; i < total; ++i) {
        if (chosen[i]) {
            int r = i / cols;
            int c = i % cols;
            matrix[r][c] = 1;
        }
    }

    free(chosen);

    return matrix;
}

int main(void) {
    int rows = 5;
    int cols = 7;
    int number_of_ones = 10;

    int **result = generate_random_matrix(rows, cols, number_of_ones);

    print_matrix(result, rows, cols);

    free_matrix(result, rows);

    return 0;
}



/*
run:

0 1 0 0 0 0 0 
0 1 0 0 1 0 1 
0 0 0 0 0 1 0 
0 0 0 1 0 0 1 
0 0 1 0 1 0 1 

*/

 



answered 5 days ago by avibootz
...