I have created a two-dimensional array with random filling of numbers not exceeding 1. I need to replace the numbers: "0" with the character "_", and "1" with the character "*". I can't do it at all. How do I do it right..?
Console.Write("Enter the width of the field: ");
int q = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the length of the field: ");
int w = Convert.ToInt32(Console.ReadLine());
int[,] myArray = new int[q, w];
Random rand = new Random();
for (int i = 0; i < q; i )
{
for (int j = 0; j < w; j )
{
myArray[i, j] = rand.Next(2);
if (i == 0)
{
Regex regex = new Regex(myArray[i, j]);
regex.Replace("_", myArray[i, j]);
}
if (j == 1)
{
Regex regex = new Regex(myArray[i, j]);
regex.Replace("*", myArray[i, j]);
}
Console.Write(myArray[i, j]);
}
Console.WriteLine();
}
CodePudding user response:
You can't replace int by char since c# is statically typed (unless you use dynamic).
If you want to fill with random _ and *, those are characters, then you want to use a character array:
var rand = new Random();
var charArray = new char[q, w];
for (int i = 0; i < q; i )
for (int j = 0; j < w; j )
charArray[i, j] = rand.Next(2) == 0 ? '_':'*';
If you want both int and char arrays, you need to declare both, and you may fill them together or separately:
var charArray = new char[q, w];
var intArray = new int[q, w];
for (int i = 0; i < q; i )
for (int j = 0; j < w; j )
{
intArray[i, j] = rand.Next(2);
charArray[i, j] = intArray[i, j] == 0 ? '_':'*';
}
If you want to do a replace, you want to use char all the time:
var charArray = new char[q, w];
for (int i = 0; i < q; i )
for (int j = 0; j < w; j )
charArray[i, j] = rand.Next(2) == 0 ? '0':'1';
for (int i = 0; i < q; i )
for (int j = 0; j < w; j )
charArray[i, j] = charArray[i, j] == '0' ? '_':'*';
My piece of advice is to keep regex, which is slower, for actual complex replacements (with wildcard, logical or, grouping, quantification) within strings (with double quote "my string").
CodePudding user response:
Try this:
for (int i = 0; i < q; i )
{
for (int j = 0; j < w; j )
{
int randomValue = rand.Next(2);
myArray[i, j] = randomValue == 0 ? "_" : "*";
Console.Write(myArray[i, j]);
}
Console.WriteLine();
}
