#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
*/