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

1 Answer

0 votes
using System;

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

        Strategy:
        - Treat the matrix as a flat index space [0 .. rows*cols - 1].
        - Randomly pick unique positions using a Boolean helper 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
    static void PrintMatrix(int[,] matrix, int rows, int cols)
    {
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++)
            {
                Console.Write(matrix[r, c] + " ");
            }
            Console.WriteLine();
        }
    }

    // Allocate a rows×cols matrix initialized to zero
    static int[,] AllocateMatrix(int rows, int cols)
    {
        // Elements are automatically initialized to zero
        return new int[rows, cols];
    }

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

        if (count > total)
            throw new ArgumentException("Requested more 1s than available cells.");

        int[,] matrix = AllocateMatrix(rows, cols);

        // Temporary array to mark chosen positions
        bool[] chosen = new bool[total];

        Random rnd = new Random();

        // Draw unique positions
        int placed = 0;
        while (placed < count)
        {
            int index = rnd.Next(total);
            if (!chosen[index]) {
                chosen[index] = true;
                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;
            }
        }

        return matrix;
    }

    static void Main()
    {
        int rows = 5;
        int cols = 7;
        int numberOfOnes = 10;

        int[,] result = GenerateRandomMatrix(rows, cols, numberOfOnes);

        PrintMatrix(result, rows, cols);
    }
}


/*
run:

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

*/

 



answered Aug 20 by avibootz
...