How to initialize a matrix with random characters in C#

1 Answer

0 votes
using System;

public class Program
{
	internal const int ROWS = 3;
	internal const int COLS = 4;
	
	public static void printMatrix(char[, ] matrix) {
		for (int i = 0; i < ROWS; i++) {
			for (int j = 0; j < COLS; j++) {
				Console.Write("{0,3}", matrix[i, j]);
			}
			Console.WriteLine();
		}
	}

	public static void initializeMatrixWithRandomCharacters(char[,] matrix) {
		string characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

		Random rand = new Random();

		for (int i = 0; i < ROWS; i++) {
			for (int j = 0; j < COLS; j++) {
				matrix[i, j] = characters[rand.Next(characters.Length)];
			}
		}
	}

	public static void Main(string[] args)
	{
		char[,] matrix = new char[ROWS, COLS];

		initializeMatrixWithRandomCharacters(matrix);

		printMatrix(matrix);
	}
}



/*
run:

  7  4  m  K
  k  A  8  5
  T  I  0  4
  
*/

 



answered May 18, 2024 by avibootz
...