Convert String[*,*] into int[*,*] in C# winform application - c#

Hello everyone I am new to programming in c#, what I am going to do is that I want to convert the 2D string array to 2D integer array, the reason for this conversion is that I want to pass that integer array to another method for some calculation. Thanks in advance for helping.
public void Matrix()
{
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
Random rnd = new Random();
int[,] matrixA = new int[a, b];
string matrixString = "";
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
matrixString += matrixA[i, j];
matrixString += " ";
}
matrixString += Environment.NewLine;
}
txtA.Text = matrixString;
txtA.TextAlign = HorizontalAlignment.Center;
}

Your code is actually pretty close. Try this:
private Random rnd = new Random();
public int[,] Matrix(int a, int b)
{
int[,] matrixA = new int[a, b];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
}
}
return matrixA;
}
What you have there is a function that does not rely on any WinForms controls and will produce your int[,] quickly and efficiently.
Let the calling code work with the WinForms controls:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
Now you can pass the matrix to anything that requires an int[,].
If you need to display the matrix then create a separate function for that:
public string MatrixToString(int[,] matrix)
{
StringBuilder sb = new();
for (int i = 0; i < matrix.GetLength(0); i++)
{
string line = "";
for (int j = 0; j < matrix.GetLength(1); j++)
{
line += $"{matrix[i, j]} ";
}
sb.AppendLine(line.Trim());
}
return sb.ToString();
}
Your calling code would look like this:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
UseTheMatrix(matrix);
txtA.Text = MatrixToString(matrix);
txtA.TextAlign = HorizontalAlignment.Center;
A sample run produces:

You can use List as a helper to store the elements of the array extracted from the string, but first I replaced the SPACE between elements in your string with a special character '|' as a separator to make it easier to extract the numbers from the string.
you can do somthing like this:
public static int[,] ConvertToInt(string matrix)
{
List<List<int>> initial = new List<List<int>>();
int lineNumber = 0;
int currenctIndex = 0;
int lastIndex = 0;
int digitCount = 0;
initial.Add(new List<int>());
foreach (char myChar in matrix.ToCharArray())
{
if (myChar == '|')
{
initial[lineNumber].Add(int.Parse(matrix.Substring(lastIndex, digitCount)));
lastIndex = currenctIndex+1;
digitCount = 0;
}
else
digitCount++;
if (myChar == '\n')
{
lineNumber++;
if(currenctIndex < matrix.Length-1)
initial.Add(new List<int>());
}
currenctIndex++;
}
int[,] myInt = new int[initial.Count, initial[0].Count];
for (int i = 0; i < initial.Count; i++)
for (int j = 0; j < initial[i].Count; j++)
myInt[i, j] = initial[i][j];
return myInt;
}

Related

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

System Generated Array

I've been working on a sorting algorithm and one condition says that the elements in the array should be program generated.
This is the code I've been working on.
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
int smallest, tmp;
Console.WriteLine("Unsorted List");
foreach (int a in myArray)
Console.Write(a + " ");
for (int i = 0; i < myArray.Length - 1; i++)
{
smallest = i;
for (int j = i + 1; j < myArray.Length; j++)
{
if (myArray[j] < myArray[smallest])
{
smallest = j;
}
tmp = myArray[smallest];
myArray[smallest] = myArray[i];
myArray[i] = tmp;
}
}
Console.WriteLine("\nSorted List Using Selection Sort:");
for (int i=0; i < myArray.Length; i++)
{
Console.Write(myArray[i] + " ");
The result of this program is just 0. How can I make the elements in array program generated? Is there a specific code block?
Please note we should use i < myArray.Length to Iterate the array instead of i < myArray.Length-1.
You can try the following code to add the elements in program generated array.
static void Main(string[] args)
{
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
int temp = 0;
int minIndex = 0;
Console.WriteLine("Unsorted List");
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < myArray.Length; i++)
{
minIndex = i;
for (int j = i; j < myArray.Length; j++)
{
if (myArray[j] < myArray[minIndex])
{
minIndex = j;
}
}
temp = myArray[minIndex];
myArray[minIndex] = myArray[i];
myArray[i] = temp;
}
Console.WriteLine("\nSorted List Using Selection Sort:");
for (int i = 0; i < myArray.Length; i++)
{
Console.Write(myArray[i] + " ");
}
Console.ReadKey();
}
Besides, I have modified the related code about Selection Sort, which makes it can produce the correct sort.
Result:
Update for generate the random array:
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
Random randNum = new Random();
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = randNum.Next(1, 100);
}
Console.WriteLine("The radnom array is ");
foreach (var item in myArray)
{
Console.WriteLine(item);
}

2d_array random numbers (10Rows, 6 COLS) not repeated to file C#

I need to streamwrite into a file.txt a 10 random numbers combinations (NOT REPEATED) like lottery program. I got everything except Non-repeated random numbers. it has to be seen (file.txt) like a 2D array with 10 combinations thx.
class Matriz
{
private int[,] array;
private int nfilas, ncols;
public void Ingresar()
{
Random aleatori = new Random();
nfilas = 10;
ncols = 6;
Console.WriteLine("\n");
array = new int[nfilas, ncols];
for (int filas = 0; filas < nfilas; filas++)
{
for (int columnas = 0; columnas < ncols; columnas++)
array[filas, columnas] = aleatori.Next(0, 50);
}
}
public void Imprimir()
{
StreamWriter fitxer = new StreamWriter(#"C:\andres\lotto649.txt");
int contador = 0;
for (int f = 0; f < nfilas; f++)
{
for (int c = 0; c < ncols; c++)
fitxer.Write(array[f, c] + " ");
fitxer.WriteLine();
contador++;
}
fitxer.WriteLine($"\n\n\tHay {contador} combinaciones de la Loteria 6/49");
fitxer.Close();
}
static void Main(string[] args)
{
Matriz array_menu = new Matriz();
array_menu.Ingresar();
array_menu.Imprimir();
}
}
Something like this should work.
Before inserting the new number in the given position, check the row thus far if the same number is already in there and if so, repeat the process until you get a number that isn't yet in there.
for (int filas = 0; filas < nfilas; filas++)
{
for (int columnas = 0; columnas < ncols; columnas++)
{
bool cont = true;
while(cont)
{
cont = false;
int newRand = aleatori.Next(0, 50);
for(int i = 0; i < columnas; i++)
if(array[filas, i] == newRand)
cont = true;
if(cont)
continue;
array[filas, columnas] = newRand;
break;
}
}
}
Alternatively, since the number is small you could also work with a list of ints and remove the given value from there.
This has the advantage, that you'll never have to redo your random number as it will always produce a valid result. The above example could (theoretically) run indefinitely long.
for (int filas = 0; filas < nfilas; filas++)
{
List<int> nums = new List<int>(49);
for(int i = 0; i < 49; i++)
nums.Add(i + 1); //num 1...49
for (int columnas = 0; columnas < ncols; columnas++)
{
int index = aleatori.Next(0, nums.Count)
array[filas, columnas] = nums[index];
nums.RemoveAt(index);
}
}

How to set random numbers in a matrix between two numbers using loops

I want to randomly generate two matrix arrays so I can later add them up and store them into a third matrix, how would I go about doing this? Nearly totally lost, here's what I have so far.
using System;
namespace question2_addingrandommatrice
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int[,] newarray = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
int ran2 = random.Next(-10, 10);
int ran1 = random.Next(-10, 10);
newarray[i, j] = ran1, ran2;
}
}
Console.ReadKey();
}
}
}
You are nearly there, you just needed one random.Next
Here is a method that does it for you
private static int[,] GenerateRandomMatrix(int x, int y)
{
var array = new int[x, y];
for (int i = 0; i < array.GetLength(0); i++)
for (int j = 0; j < array.GetLength(1); j++)
array[i, j] = random.Next(-10, 10);
return array;
}
Add pepper and salt to taste
Usage
// 3*3 random matrix
var matrix = GenerateRandomMatrix(3,3);
Additional Resources
Multidimensional Arrays (C# Programming Guide)
You can simply do this.
Random random = new Random();
int[,] newarray = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
newarray[i, j] = random.Next(-10, 10); ;
}

how do i display the table for a 2D array?

I need to fill an array and display that array to the console (in table format).
Here is what I have so far:
static void Main()
{
//Declare variables, strings and constants.
const int ROWS = 10;
const int COLS = 5;
const int MIN = 1;
const int MAX = 100;
int total = 0;
int[,] numbers = new int[ROWS, COLS];
Random rand = new Random();
//Populate the array
for (int r = 0; r < ROWS; ++r)
{
for (int c = 0; c < COLS; ++c)
{
numbers[r, c] = rand.Next(MIN, MAX + 1);
}
}
//Display the array to console (table format)
for (int r = 0; r < numbers.GetLength(0); ++r)
{
for (int c = 0; c < numbers.GetLength(1); ++c)
{
Console.Write("{0,6} ", numbers[r, c]);
if (c % 5 == 0) Console.WriteLine();
}
}
When i do this, my display if off by 1 and doesn't align properly for a 10x5 table.
You could check if the column index plus one, c + 1, is equal to the given column count, COLS, then write a new line:
if (c + 1 == COLS) Console.WriteLine();
Another way is to print a new line after all columns are printed:
for (int r = 0; r < numbers.GetLength(0); ++r)
{
for (int c = 0; c < numbers.GetLength(1); ++c)
{
Console.Write("{0,6} ", numbers[r, c]);
}
Console.WriteLine();
}
This happens because of your next line:
if (c%5 == 0) Console.WriteLine();
Notice that the first output, r=0, c=0, so it prints a new line

Categories