Problem with UnitTest(Method doesn`t work properly) - c#

I have a matrix calculator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp11
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите размерность первой матрицы: ");
int[,] A = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
for (int i = 0; i < A.GetLength(0); i++)
{
for (int j = 0; j < A.GetLength(1); j++)
{
Console.Write("A[{0},{1}] = ", i, j);
A[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Введите размерность второй матрицы: ");
int[,] B = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
for (int i = 0; i < B.GetLength(0); i++)
{
for (int j = 0; j < B.GetLength(1); j++)
{
Console.Write("B[{0},{1}] = ", i, j);
B[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("\nМатрица A:");
Print(A);
Console.WriteLine("\nМатрица B:");
Print(B);
Console.WriteLine("\nМатрица C = A * B:");
int[,] C = Multiplication(A, B);
Print(C);
}
static int[,] Multiplication(int[,] a, int[,] b)
{
if (a.GetLength(1) != b.GetLength(0)) throw new Exception("Матрицы нельзя перемножить");
int[,] r = new int[a.GetLength(0), b.GetLength(1)];
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < b.GetLength(1); j++)
{
for (int k = 0; k < b.GetLength(0); k++)
{
r[i, j] += a[i, k] * b[k, j];
}
}
}
return r;
}
static void Print(int[,] a)
{
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < a.GetLength(1); j++)
{
Console.Write("{0} ", a[i, j]);
}
Console.WriteLine();
}
}
static int[,] Multiplication_test(int[,] a_test, int[,] b_test) // типо забыл поменять что-то
{
int[,] r = new int[a_test.GetLength(0), b_test.GetLength(1)];
for (int i = 0; i < a_test.GetLength(0); i++)
{
for (int j = 0; j < b_test.GetLength(1); j++)
{
for (int k = 0; k < b_test.GetLength(0); k++)
{
r[i, j] -= a_test[i, k] * b_test[k, j];
}
}
}
return r;
}
}
}
And I have a UnitTest Program
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ConsoleApp11;
using System.Threading.Tasks;
namespace UnitTestProject2
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
int[,] A = { { 1, 2, 3 }, { 3, 4, 5 } };
int[,] B = { { 3, 4 }, { 1, 2 }, { 3, 5 } };
int[,] expected = { { 14, 23 }, { 28, 45 } };
int [,] actual = Multiplication_test(A, B);
Assert.AreEqual(expected, actual, "Multiplication_test1 isn`t correct ");
}
}
}
All in all is fine , but i have a problem
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'Multiplication_test' does not exist in the current context UnitTestProject
I did more things but nothing changed...
I tried change static method to public but nothing changed. Please help me !!!

Multiplication_test is a static method on Program, so it should be Program.Multiplication_test(...)

Related

Why can't get matrix what I passed to Thread?

I want to do some basic stuff: get a matrix, and iterate on it with multiple threads. For example, if I have a 20x20 sized matrix, and I have 4 threads, then the first Thread have to iterate on the 5x20 sized matrix, the second one has to iterate on the same size, but from the 6th row to the 10th one, and so on. But, my program gets only the first part, the second, and third, fourth threads can't see their submatrixes. Why? Can anyone help me with this?
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace multi_thred_test
{
class thredData
{
public int my_simulation_size;
public int[,] my_simulation;
public string my_path;
public int my_nrOfAvailableThreads;
public int my_oneThreeadSubsimulationSize;
public thredData(ref int simsize, ref int[,] simu, ref string path, ref int availabelthrd, ref int subsimsize )
{
my_simulation_size = simsize;
my_simulation = new int[simsize, simsize];
for (int i = 0; i < simsize; i++)
{
for (int j = 0; j < simsize; j++)
{
my_simulation[i, j] = simu[i, j];
}
}
my_path = path;
my_nrOfAvailableThreads = availabelthrd;
my_oneThreeadSubsimulationSize = subsimsize;
}
}
class Program
{
public static int simulation_size = 20;
public static int[,] simulation = new int[20, 20];
public static string path = Directory.GetCurrentDirectory();
public static int nrOfAvailableThreads = Environment.ProcessorCount;
public static int oneThreeadSubsimulationSize = simulation_size / nrOfAvailableThreads;
public static thredData tmp;
public static void Main(string[] args)
{
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
simulation[idx, jdx] = idx * 100 + jdx;
}
}
StreamWriter sw = new StreamWriter(path + "_matrix.txt");
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
sw.Write(simulation[idx, jdx]+" ");
}
sw.WriteLine(" ");
}
sw.Close();
tmp = new thredData(ref simulation_size, ref simulation, ref path, ref nrOfAvailableThreads, ref oneThreeadSubsimulationSize);
//generate threads
for (int thrdnr = 0; thrdnr < nrOfAvailableThreads; thrdnr++)
{
Thread newThread = new Thread(ThreadMethod);
newThread.Name = Convert.ToString(thrdnr);
newThread.Start();
}
Console.ReadKey();
}
private static void ThreadMethod()
{
Thread thr = Thread.CurrentThread;
int simulationSize = Convert.ToInt32(thr.Name);
int thrd_simulation_size;
int[,] thrd_simulation;
string thrd_path;
int thrd_nrOfAvailableThreads;
int thrd_oneThreeadSubsimulationSize;
lock (tmp)
{
thrd_simulation_size = tmp.my_simulation_size;
thrd_simulation = new int[thrd_simulation_size, thrd_simulation_size];
for (int i = 0; i < tmp.my_simulation_size; i++)
{
for (int j = 0; j < tmp.my_simulation_size; j++)
{
thrd_simulation[i, j] = tmp.my_simulation[i, j];
}
}
thrd_path = tmp.my_path;
thrd_nrOfAvailableThreads = tmp.my_nrOfAvailableThreads;
thrd_oneThreeadSubsimulationSize = tmp.my_oneThreeadSubsimulationSize;
}
for (int i = thrd_simulation_size * simulationSize; i < thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name +":"+ thrd_simulation[i,j] + " ");
}
Console.Write("\n");
}
}
}
}
Problem solved, the log part was wrong:
for (int i = thrd_oneThreeadSubsimulationSize * simulationSize; i < (thrd_oneThreeadSubsimulationSize * simulationSize) +thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name + ":" + thrd_simulation[i, j] + " ");
}
Console.Write("\n");
}

Memory error NZEC when using C# on HackerEarth

I am solving a question on HackerEarth. The test case passes successfully, but the rest of the cases show a NZEC error. I know NZEC stands for Non Zero Exit Code but I am not sure why this is happening here.
Any insight about why this happens and how I can optimize my code (preferably without changing the logic) will help.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int t = int.Parse(Console.ReadLine());
int[] arr = new int[3];
for(int m = 0; m < t; m++)
{
arr[m] = int.Parse(Console.ReadLine());
}
for (int n = 0; n < t; n++)
{
int i, j;
for (i = 0; i < arr[n]; i++)
{
for (j = 0; j < 2 * arr[n]; j++)
{
if (j <= i || j >= 2 * arr[n] - 1 - i)
{
Console.Write("*");
}
else
{
Console.Write("#");
}
}
Console.WriteLine("\n");
}
Console.WriteLine("\n");
}
}
}

Read array 2D and output as table C#

I am new at programming in C# and I'm trying to display to whole content of a matrix in the format of a table, however what I got so far is to read the enum and read one line from the matrix. Instead I need to read multiple lines from the matrix and output as a table.
when I run the program I get to insert data twice in row and the output should've been this data inside a table, but only one line is being shown.
Here's the code:
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0); j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
private static void InsertData<T>(string[,] matrix)
{
// int newId = generateId(ref id);
int n = getInsertIndex(matrix), id = 1;
matrix[n, 0] = Convert.ToString(id++);
int x = matrix.GetLength(1) - 1;
matrix[n, x] = "true";
for (var j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"\nInsert {GetHeader<T>(j)}: ");
matrix[0, j] = Console.ReadLine();
} while (string.IsNullOrEmpty(matrix[0, j]));
}
}
private static void ListData<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var l = 0; l < matrix.GetLength(0); l++)
{
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[0, i];
}
}
PrintRow(array);
PrintLine();
}
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
private static void ShowHeader<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = GetHeader<T>(i);
}
PrintLine();
PrintRow(array);
PrintLine();
}
private static void PrintLine()
{
Console.WriteLine(new string('-', Console.WindowWidth - 1));
}
private static void PrintRow(IReadOnlyCollection<string> columns)
{
var width = (Console.WindowWidth - 1 - columns.Count) / columns.Count;
var row = columns.Aggregate("|", (current, column) => current + AlignCentre(column, width) + "|");
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
return string.IsNullOrEmpty(text)
? new string(' ', width)
: text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
enum ClientHeader { Id, Name, Surname, Addres, CodPostal, Telephone, Email, State };
private static void Main()
{
var client = new string[4, 7];
InsertData<ClientHeader>(client);
Console.Clear();
InsertData<ClientHeader>(client);
ShowHeader<ClientHeader>(client);
ListData<ClientHeader>(client);
}
}
}
There are 2 issues:
1) In the InsertData() function, you want to update the n th row.
Replace
matrix[0, j] = Console.ReadLine();
by
matrix[n, j] = Console.ReadLine();
2) In the ListData() function you want to show each row, so you need to move the array variable into the first for loop. Replace array[i] = matrix[0, i] with array[i] = matrix[l, i] because you are displaying the l th row.
private static void ListData<T>(string[,] matrix)
{
for (var l = 0; l < matrix.GetLength(0); l++)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[l, i];
}
PrintRow(array);
}
PrintLine();
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
public class Program
{
private static void Main()
{
List<List<string>> data = new List<List<string>>() {
new List<string>() { "Name", "Age", "Weight"},
new List<string>() { "John", "33", "180"},
new List<string>() { "Mary", "32", "125"},
new List<string>() { "Harry", "40", "200"}
};
DataTable dt = new DataTable();
for (int i = 0; i < data.Count; i++)
{
if (i == 0)
{
foreach (string col in data[i])
{
dt.Columns.Add(col);
}
}
else
{
dt.Rows.Add(data[i].ToArray());
}
}
}
}
}

How to make a matrix multiplication in a task

I am unable unable to get the product of matrices in a task in order to run it
in several instances. I think the task is not properly doing the multiplication and calling several 0's.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _010029428_Multiplicacion
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n;
Random rnd = new Random((int)DateTime.Now.Ticks & 0x000fff);
Console.WriteLine("Ingrese el numero de renglones y columnas: ");
m = Convert.ToInt32(Console.ReadLine());
n = Convert.ToInt32(Console.ReadLine());
int[,] a = new int[m, n];
Console.WriteLine("first Matrix");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
a[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("First matrix is: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
int[,] b = new int[m, n];
Console.WriteLine("Second Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
b[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("The second matrix is:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("The result is :");
int[,] c = new int[m, n];
var multiplicacion = new Task(() =>
{
for (j = 0; j < n; j++)
{
c[i, j] = 0;
for (int k = 0; k < n; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
});
for (i = 0; i < m; i++)
{
multiplicacion.Start();
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
}
}
}
The code is using multiplicacion.start() to run it asynchronously
Not sure what the problem may be
There are several problems.
First: You cannot create just one task and run it multiple times at once. New Task() must be created for each value of "i".
Second: You cannot use global variable ("j") and mutate it in a task that runs asynchronously, without proper synchronization. This would result in program crash or wrong result. Each task must have it's own (local) variable ("jj") if it needs to change it. Read-only variables (i, a, b, c, m, n) are usually safe to use, but it is better to pass them as arguments.
Third: You must wait for all tasks to finish before you write result to screen.
Four: Running task asynchronously has significant performance overhead. So unless you matrices are really huge (probably at least hundreads of rows and columns), calculating result in several asynchronous tasks is probably much slower than simple synchronous calculation on main thread.
Example of how to make it work follows. Code is still ugly and not wery good, but should work and give you some starting point for further improvements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _010029428_Multiplicacion
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n;
Random rnd = new Random((int)DateTime.Now.Ticks & 0x000fff);
Console.WriteLine("Ingrese el numero de renglones y columnas: ");
m = Convert.ToInt32(Console.ReadLine());
n = Convert.ToInt32(Console.ReadLine());
int[,] a = new int[m, n];
Console.WriteLine("first Matrix");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
a[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("First matrix is: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
int[,] b = new int[m, n];
Console.WriteLine("Second Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
b[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("The second matrix is:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("The result is :");
int[,] c = new int[m, n];
Task[] tasks = new Task[m];
for (i = 0; i < m; i++)
{
var multiplicacion = new Task((parameter) =>
{
int ii = (int)parameter;
for (int jj = 0; jj < n; jj++)
{
c[ii, jj] = 0;
for (int k = 0; k < n; k++)
{
c[ii, jj] += a[ii, k] * b[k, jj];
}
}
},
i);
tasks[i] = multiplicacion;
multiplicacion.Start();
}
Task.WaitAll(tasks);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

How to get whole list of processes in decreasing order of their thread count ( C# ) [duplicate]

This question already has answers here:
How to count the amount of concurrent threads in .NET application?
(2 answers)
Closed 7 years ago.
How to get whole list of processes in decreasing order of their thread count ( C# )
You could try this,
Process[] processList = Process.GetProcesses().OrderByDescending(x => x.Threads.Count).ToArray();
You could do the following:
private void fuc()
{
System.Diagnostics.Process[] procArray;
procArray = System.Diagnostics.Process.GetProcesses();
List<KeyValuePair<string, int>> threads = new List<KeyValuePair<string,int>>();
for (int i = 0; i < procArray.Length; i++)
{
var element = new KeyValuePair<string, int>(procArray[i].ProcessName, procArray[i].Threads.Count);
threads.Add(element);
}
threads.Sort(OrderAsc);
}
static int OrderAsc(KeyValuePair<string, int> a, KeyValuePair<string, int> b)
{
return a.Value.CompareTo(b.Value);
}
Its a big code (can become more compact)......but finally got the answer....thank you so much #kuruban #Gnqz #utility #derape
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process[] procArray;
procArray = System.Diagnostics.Process.GetProcesses();
String[,] arr = new String[300,2];
String max, maxi;
int k;
for (k = 0; k < procArray.Length; k++)
{
arr[k, 0] = procArray[k].ProcessName;
arr[k, 1] = (procArray[k].Threads.Count).ToString();
}
for (int i = 0; i < procArray.Length; i++)
{
for (int j = i; j < procArray.Length; j++)
{
if (int.Parse(arr[i, 1]) < int.Parse(arr[j, 1]))
{
max = arr[j, 0];
arr[j, 0] = arr[i, 0];
arr[i, 0] = max;
maxi = arr[j, 1];
arr[j, 1] = arr[i, 1];
arr[i, 1] = maxi;
}
}
}
for (int i = 0; i < procArray.Length; i++)
{
Console.WriteLine("{0} {1}", arr[i, 0], arr[i, 1]);
}
}
}
}

Categories

Resources