So, I have to do homework about methods in c#. I am confused about some points. I wrote methods (they may be wrong) but I don't know how to call them. How can I write this part? For example finding max value. What can I write? I tried a lot of times but couldn't handle it.
Also, this code has to be kept in a txt file but doesn't.
public static void WriteData(StreamWriter sw)
{
int[,] a = new int[4, 6];
Random rnd = new Random();
for (int i = 0; i < a.GetLength(0); i++)
{
for (int J = 0; J < a.GetLength(1); J++)
{
a[i, J] = rnd.Next(10, 100);
}
}
Console.WriteLine("\nMATRIX:");
for (int i = 0; i < a.GetLength(0); i++)
{
for (int J = 0; J < a.GetLength(1); J++)
{
Console.Write("{0,-4}", a[i, J]);
}
Console.WriteLine();
}
Console.WriteLine("\nTRANSPOSE:");
for (int i = 0; i < a.GetLength(1); i++)
{
for (int J = 0; J < a.GetLength(0); J++)
{
Console.Write("{0,-4}", a[J, i]);
}
Console.WriteLine();
}
}
public static void DisplayMatrix(int[,] a)
{
Console.WriteLine("{0}", a);
}
public static int MaxNumber(int[] a)
{
int max = a[0];
for (int i = 0; i < a.Length; i++)
{
if (max < a[i])
{ max = a[i]; }
}
return max;
}
public static void DisplayOddOrEvenForMax(int max)
{
if (max % 2 == 0)
{
Console.WriteLine("Number is even");
}
else
{
Console.WriteLine("Number is odd");
}
}
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("MyMatrix.txt", true);
WriteData(sw);
sw.Close();
`
Methods are (usually) either attached to a class or are static
if you have a class like this:
class MyClass {
void myMethod() {
//do something
}
}
then you have to create an instance of that class , so something like this:
MyClass foo = new MyClass() //here foo is the name of the instance
and then call that method on that instance
foo.myMethod()
if the method is static like this:
class MyClass {
static void myMethod() {
//do something
}
}
then that method does can be run directly by calling it, along with the class that contains it, so something like this:
MyClass.myMethod()
I hope this helped
Related
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>();
}
i defined the array and the functions but i'm having trouble calling the function, should i call a function using class name or object
public static string PrintArray (int [,] arr)
{
string output = "";
for (int i = 0; i<arr.GetLength(0);i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
output += arr[i,j];
output = output.Substring(0, output.Length)+"/n";
}
return output;
}
public static void Fill(int[,] arr,int min, int max)
{
Random r = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
{
arr[i] = r.Next(min, max);
for (int j = 0; j < arr.GetLength(1); j++)
{
arr[i,j] = r.Next(min, max);
}
}
}
If you have static methods, they must be called using the class name. You would only call from an object if it was an instance (non-static) method, it is not possible to call a static method from an instance of an object, or an instance method from a static class name.
In your case, as you have defined static methods, you must reference them in a static way. e.g., if your class was called ArrayHelper
public class ArrayHelper
{
public static string PrintArray (int [,] arr)
{
string output = "";
for (int i = 0; i<arr.GetLength(0);i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
output += arr[i,j];
output = output.Substring(0, output.Length)+"/n";
}
return output;
}
public static void Fill(int[,] arr,int min, int max)
{
Random r = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
{
arr[i] = r.Next(min, max);
for (int j = 0; j < arr.GetLength(1); j++)
{
arr[i,j] = r.Next(min, max);
}
}
}
}
You could use it like so
var array = ...
ArrayHelper.Fill(array, 10, 20);
I cannot get this method to work. It intends to multiply a matrix by a given one. Could someone help me to correct it please?
class Matriz
{
public double[,] structure;
//Other class methods
public void multiplyBy(Matrix m)
{
if (this.structure.GetLength(1) == m.structure.GetLength(0))
{
Matriz resultant = new Matriz(this.structure.GetLength(0), m.structure.GetLength(1));
for (int i = 0; i < this.structure.GetLength(0) - 1; i++)
{
for (int j = 0; j < m.structure.GetLength(1) - 1; j++)
{
resultant.structure[i, j] = 0;
for (int z = 0; z < this.structure.GetLength(1) - 1; z++)
{
resultant.structure[i, j] += this.structure[i, z] * m.structure[z, j];
}
}
}
this.structure= resultant.structure;
}
else
{
Console.WriteLine("Selected matrixs cannot be multiply");
}
}
}
Read this MSDN Magazine article by James McCaffrey and use the code below as an extension method. They use a jagged array which is more convenient and sometimes faster than a 2D array. Change any data[i][j] to data[i,j] to make the code work with a 2D array.
public static double[] MatrixProduct(this double[][] matrixA,
double[] vectorB)
{
int aRows=matrixA.Length; int aCols=matrixA[0].Length;
int bRows=vectorB.Length;
if (aCols!=bRows)
throw new Exception("Non-conformable matrices in MatrixProduct");
double[] result=new double[aRows];
for (int i=0; i<aRows; ++i) // each row of A
for (int k=0; k<aCols; ++k)
result[i]+=matrixA[i][k]*vectorB[k];
return result;
}
public static double[][] MatrixProduct(this double[][] matrixA,
double[][] matrixB)
{
int aRows=matrixA.Length; int aCols=matrixA[0].Length;
int bRows=matrixB.Length; int bCols=matrixB[0].Length;
if (aCols!=bRows)
throw new Exception("Non-conformable matrices in MatrixProduct");
double[][] result=MatrixCreate(aRows, bCols);
for (int i=0; i<aRows; ++i) // each row of A
for (int j=0; j<bCols; ++j) // each col of B
for (int k=0; k<aCols; ++k)
result[i][j]+=matrixA[i][k]*matrixB[k][j];
return result;
}
public static double[][] MatrixCreate(int rows, int cols)
{
// creates a matrix initialized to all 0.0s
// do error checking here?
double[][] result=new double[rows][];
for (int i=0; i<rows; ++i)
result[i]=new double[cols];
// auto init to 0.0
return result;
}
This is the modified version of my method, as far as I've been testing this approach works fine.
public void multiplicarPor(Matriz m)
{
if (this.estructura.GetLength(1) == m.estructura.GetLength(0))
{
Matriz resultante = new Matriz(this.estructura.GetLength(0), m.estructura.GetLength(1));
for (int i = 0; i < this.estructura.GetLength(0); i++)
{
for (int j = 0; j < m.estructura.GetLength(1); j++)
{
resultante.estructura[i, j] = 0;
for (int z = 0; z < this.estructura.GetLength(1); z++)
{
resultante.estructura[i, j] += this.estructura[i, z] * m.estructura[z, j];
}
}
}
this.estructura = resultante.estructura;
}
else
{
Console.WriteLine("No se pueden multiplicar estas matrices");
}
}
public static void Sort2DArray(int[,] matrix)
{
var numb = new int[matrix.GetLength(0) * matrix.GetLength(1)];
int i = 0;
foreach (var n in matrix)
{
numb[i] = n;
i++;
}
Array.Sort(numb);
int k = 0;
for (i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = numb[k];
k++;
}
}
}
I'm curious how can I make this method generic. I wish that it could sort double matrices, string matrices and so on and so forth.
You can use IComparable interface as a generic type T specifier.
See those links
How to Sort 2D Array in C#
How do I sort a two-dimensional array in C#?
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=151
I have solved it. the method looks like this:
public static void Sort2DArray<T>(T[,] matrix)
{
var numb = new T[matrix.GetLength(0) * matrix.GetLength(1)];
int i = 0;
foreach (var n in matrix)
{
numb[i] = n;
i++;
}
Array.Sort(numb);
int k = 0;
for (i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = numb[k];
k++;
}
}
}
I am trying to create a function that accepts 5 integers, holds them in an array and then passes that array back to the main. I have wrestled with it for a couple of hours and read some MSDN docs on it, but it hasn't "clicked". Can someone please shed some light as to what I am doing wrong?
Errors:
Not all code paths return a value;
something about invalid arguments:
Code:
using System;
using System.IO;
using System.Text;
namespace ANumArrayAPP
{
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
}
}
}
The parameter to ReadInNum is a single int, but you're trying to pass an array. You have to make the parameter match what you're trying to pass in. For example:
static void ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readIn[i] = int.Parse(Console.ReadLine());
}
}
That will fill the array you pass into the method. Another alternative is to pass in how many integers you want, and return the array from the method:
static int[] ReadInNum(int count)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
Console.WriteLine("Please enter an interger");
values[i] = int.Parse(Console.ReadLine());
}
return values;
}
You'd call this from Main like this:
int[] input = ReadInNum(5);
for (int a = 0; a < 5; a++)
{
Console.Write(input[a]);
}
You should complete your function with return statement since its return type is not void. Also, you should change your return type to int[] since your return an array of ints, not just one int:
static int[] ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readInn;
}
You should also change your main function in order to get the result of the function ReadInNum. It seems to me that you don't really use the parameter so you can remove it, if you don't have special attention:
static void Main()
{
int j;
int[] i = ReadInNum(j);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
To summarize zome aswer already here, there are two ways to go about it:
1. Pass an array into the method
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(i[a]); // !
}
}
static int ReadInNum(int[] readIn)
{
for (int i = 0; i < rreadIn.Length; i++)
...
}
2. Return an array
static void Main()
{
// int[] i = new int[5];
int[] i = ReadInNum(5);
for (int a = 0; a < i.Length; a++)
{
Console.Write(i[a]); // !
}
}
static int[] ReadInNum(int size)
{
int[] readIn = new int[size];
for (int i = 0; i < readIn.Length; i++)
...
}
Pass an array to the function:
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int[] ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readIn;
}
}
Notice how I returned an int[] from ReadInNum. This isn't necessary but it makes the code more readable since it's not more obvious that you're planning on changing readIn.