I am new in C# and I have a problem with for loops in lists.
I have a list with numbers (called alpha) which go from 0 to 7.
alpha0=1
alpha1=2
alpha2=3
...
alpha7=8
Now I want to create a matrix containing all these alphas in this way and then I want to transpose it:
I've tried to write the transposed one directly but it gives me error or better I am wrong with the syntax (see last string of my code). Could somebody help me?
I called startinglist my list with alphas.
List<List<double>> arr = new List<List<double>>();
for (int col = 0; col < 8; col++)
for (int row = 0; row < 7; row++)
arr[col, row].Add(startinglist[col]);
Try below code:
var size = 8;
var alpha = Enumerable.Range(1, size).ToArray();
var matrix = new int[size, size + 1];
for (int i = 0; i < size; i++)
{
// Assign values on the diagonal.
matrix[i, i] = alpha[i];
matrix[i, i + 1] = 1 - alpha[i];
}
Try this:
var size = 8;
int[] alpha = Enumerable.Range(1, size).ToArray();
int[][] C = new int[size - 1][];
for(int i = 0 ; i < size - 1; i++)
{
C[i] = new int[size];
C[i][i] = alpha[i];
C[i][i + 1] = 1 - alpha[i + 1];
}
Edit:
Since you have alpha already defined as a list, you may use this:
Edit2:
Changed int to double:
double[][] C = new double[alpha.Count - 1][];
for(int i = 0 ; i < alpha.Count - 1; i++)
{
C[i] = new double[alpha.Count];
C[i][i] = alpha[i];
C[i][i + 1] = 1 - alpha[i + 1];
}
static void Main(string[] args)
{
Random r = new Random();
int[,] x = new int[10,8];
int[] temp = new int[x.Length];
// two dimensional array and i want for three dimensional array
for(int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 100);
for(int j = 0; j < i; j++)
{
if(temp[i] == temp[j])
{
i--;
break;
}
}
}
for(int i = 0, index = 0; i < x.GetLength(0); i++)
{
for(int j = 0; j < x.GetLength(1); j++)
{
x[i, j] = temp[index++]; //two dimensional array unique numbers
Console.Write(x[i, j] + " ");
}
}
// i want do it as for 3D and 4 D array unique numbers like that method what can i change or add?
It's pretty straight forward to do what you're doing for higher dimensions.
Here's my code for 3D:
var r = new Random();
int [,,] x = new int[10, 8, 8];
var count =
Enumerable
.Range(0, x.Rank)
.Select(y => x.GetLength(y))
.Aggregate((y, z) => y * z);
var values =
Enumerable
.Range(10, count)
.OrderBy(y => r.Next())
.ToArray();
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
x[i, j, k] = values[v++];
To change it to 4D these lines change:
int [,,,] x = new int[10, 8, 8, 12];
// ...
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
for (var l = x.GetLowerBound(3); l <= x.GetUpperBound(3); l++)
x[i, j, k, l] = values[v++];
Now, in this code I have explicitly called GetLowerBound as well as GetUpperBound as it is possible in .NET code to have a non-zero based array.
Also, rather than repeatedly re-try getting random numbers until you have unique numbers I simply generated a sequence of unique numbers and then randomly sorted them. That's a little different from your original code. You needed 80 (10 x 8) random values and you were choosing from values ranging from 10 to 99 inclusive. So you had some holes in your numbers.
Random r = new Random();
int[,,] x = new int[10, 8, 8];
int[] temp = new int[x.Length];
#region one dimensional array unique numbers.
for (int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 650);
for (int j = 0; j < i; j++)
{
if (temp[i] == temp[j])
{
i--;
break;
}
}
}
#endregion
for (int i = 0, index = 0; i < x.GetLength(0); i++)
{
for (int j = 0; j < x.GetLength(1); j++)
{
for (int k = 0; k < x.GetLength(2); k++)
{
x[i, j, k] = temp[index++];
Console.Write(x[i, j, k] + " ");
}
Console.WriteLine();
}
}// i think it's correct code i've changed it
I'm trying to make a program that: When given a 4 digit number (for example, 1001) it sums the digits of that number, for 1001 this is 1 + 0 + 0 + 1 = 2, than it finds all sequences of 6 numbers from 1 to 6 (including permutations, i.e. 1*1*1*1*1*2 is different than 2*1*1*1*1*1) whose product is that number.
The result should be printed on the console in the following format: each sequence of 6 numbers, with their Morse representation, separated with a single pipe: 1 is .---- , 2 is ..---: .----|.----|.----|.----|..---|, on a new row the next permutation: .----|.----|.----|..---|.----| and so on.
The problem is, my solution doesn't show the correct answers, not even the correct number of them.
Here's my code (and please, if possible, tell me where my mistake is, and not some one line hack solutions to the problem with LINQ and regex and God knows what):
string n = Console.ReadLine();
string[] digitsChar = new string[n.Length];
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
int morseProduct = digits.Sum();
Console.WriteLine(morseProduct);
List<int> morseCodeNumbers = new List<int>();
for (int i = 1; i < 6; i++)
{
for (int j = 1; i < 6; i++)
{
for (int k = 1; i < 6; i++)
{
for (int l = 1; i < 6; i++)
{
for (int m = 1; i < 6; i++)
{
for (int o = 1; o < 6; o++)
{
int product = i * j * k * l * m * o;
if (product == morseProduct)
{
morseCodeNumbers.Add(i);
morseCodeNumbers.Add(j);
morseCodeNumbers.Add(k);
morseCodeNumbers.Add(l);
morseCodeNumbers.Add(m);
morseCodeNumbers.Add(o);
}
}
}
}
}
}
}
int numberOfNumbers = morseCodeNumbers.Count;
string[] morseCodes = new string[] { "-----", ".----", "..---", "...--", "....-", "....." };
for (int i = 0; i < numberOfNumbers; i++)
{
int counter = 0;
if (i % 5 == 0)
{
Console.WriteLine();
counter = 0;
}
if (counter < 5)
{
int index = morseCodeNumbers[i];
Console.Write(morseCodes[index] + "|");
counter++;
}
A lot of your for-loop conditions refer to i instead of j,k,l and m. The same for the increment part. For example:
for (int j = 1; i < 6; i++)
should be
for (int j = 1; j < 6; j++)
Furthermore if the range is from 1 to 6 you need to change < to <=, see:
for (int i = 1; i <= 6; i++)
You don't need to convert the string to a string array to get the int array of digits btw, so while this is correct:
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
you could it do like that (sry for LINQ):
var digits = n.Select(c=>(int)char.GetNumericValue(c) ).ToArray();
Like described in the title, is there some library in the Microsoft framework which allows to multiply two matrices or do I have to write my own method to do this? // I've got an answer to this by now
Second question:
I wrote this multi class with a MultiplyMatrix method but it doesn't work like I want to. Can anyone help and tell where I made a mistake?
class multi
{
public void MultiplyMatrix(double[,] _A, double[,] _B, int _n, int _m, int _r)
{
int n, m, r;
double si;
n = _n;
m = _m;
r = _r;
double[,] A = new double[n, m];
double[,] B = new double[m, r];
double[,] C = new double[n, r];
A = _A;
B = _B;
try
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < r; j++)
{
si = 0;
for (int k = 0; k < m; k++)
{
si += A[i, m + k] + B[k, r + j];
}
C[i, r + j] = si;
}
}
for (int i = 0; i < C.Length; i++)
{
for (int j = 0; j < C.Length; j++)
{
Console.Write(C[i, j]+" ");
if (j % 3 == 0)
Console.WriteLine();
}
}
}
catch (IndexOutOfRangeException) { } // I always get this exception
}
}
I forgot to tell: I want to make a webservice to multiply on it.
Thanks:)
Multiplication of 2 matrixes:
public double[,] MultiplyMatrix(double[,] A, double[,] B)
{
int rA = A.GetLength(0);
int cA = A.GetLength(1);
int rB = B.GetLength(0);
int cB = B.GetLength(1);
if (cA != rB)
{
Console.WriteLine("Matrixes can't be multiplied!!");
}
else
{
double temp = 0;
double[,] kHasil = new double[rA, cB];
for (int i = 0; i < rA; i++)
{
for (int j = 0; j < cB; j++)
{
temp = 0;
for (int k = 0; k < cA; k++)
{
temp += A[i, k] * B[k, j];
}
kHasil[i, j] = temp;
}
}
return kHasil;
}
}
Whilst there's no built in Maths framework to do this in .NET (could use XNA's Maths library), there is a Matrix in the System.Windows.Media namespace. The Matrix structure has a Multiply method which takes in another Matrix and outputs a Matrix.
Matrix matrix1 = new Matrix(5, 10, 15, 20, 25, 30);
Matrix matrix2 = new Matrix(2, 4, 6, 8, 10, 12);
// matrixResult is equal to (70,100,150,220,240,352)
Matrix matrixResult = Matrix.Multiply(matrix1, matrix2);
// matrixResult2 is also
// equal to (70,100,150,220,240,352)
Matrix matrixResult2 = matrix1 * matrix2;
This is mainly used for 2D transformation:
Represents a 3x3 affine transformation
matrix used for transformations in 2-D
space.
but if it suits your needs, then there's no need for any third party libraries.
Although you can multiply matrices by an iterative approach (for loops), performing the calculations with linear algebra will clean up your code and will give you performance gains that are several times faster!
There is a free library available in nuget - MathNet.Numerics. It makes it extremely easy to multiply matrices:
Matrix<double> a = DenseMatrix.OfArray(new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
Matrix<double> b = DenseMatrix.OfArray(new double[,] { { 1 }, { 2 }, { 3 } });
Matrix<double> result = a * b;
It has no dependencies and can be used in .net core 2.0, making it an excellent choice to avoid iterative matrix multiplication techniques and take advantage of linear algebra.
There is nothing built into .NET. You will have to write the multiplication yourself or use some third party library. I've blogged about one way to achieve this comparing two different implementations : a standard naive algorithm and one using unsafe code.
CSML - C# Matrix Library - is a compact and lightweight package for numerical linear algebra. Many matrix operations known from Matlab, Scilab and Co. are implemented.
See this!
There are no such built in libraries. Unless you are using XNA - it has a Matrix class, though it is limited and designed for 3D games.
There are many matrix libraries for .NET though.
namespace matrix_multiplication
{
class Program
{
static void Main(string[] args)
{
int i, j;
int[,] a = new int[2, 2];
Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("First matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(a[i,j]+"\t");
}
Console.WriteLine();
}
int[,] b = new int[2, 2];
Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
b[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("second matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Matrix multiplication is:");
int[,] c = new int[2, 2];
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
c[i,j]=0;
for (int k = 0; k < 2; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(c[i, j]+"\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
output
Enter no for 2*2 matrix
8
7
6
0
First matrix is:
8 7
6 0
Enter no for 2*2 matrix
4
3
2
1
second matrix is:
4 3
2 1
Matrix multiplication is:
46 31
24 18
Below is the method to multiply int[3,4] matrix with int[4,3] matrix, it has time complexity of O(n cube) or Cubic time
class Program
{
static void Main(string[] args)
{
MultiplyMatrix();
}
static void MultiplyMatrix()
{
int[,] metrix1 = new int[3,4] { { 1, 2,3,2 }, { 3, 4,5,6 }, { 5, 6,8,4 } };
int[,] metrix2 = new int[4, 3] { { 2, 5, 3 }, { 4, 5, 1 }, { 8, 7, 9 }, { 3, 7, 2 } };
int[,] metrixMultplied = new int[3, 3];
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
for(int i=0;i<4;i++)
{
metrixMultplied[row, col] = metrixMultplied[row, col] + metrix1[row, i] * metrix2[i, col];
}
Console.Write(metrixMultplied[row, col] + ", ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
Here is my code : 4*4 matrix
for (int i = 0; i < 4; i++)
{
int column = 0;
while (column < 4)
{
int count = 0;
for (int j = 0; j < 4; j++)
{
matrixResult[i, column] += Convert.ToInt32(matrixR[i, j] * matrixT[count, column]);
count = count + 1;
}
column = column + 1;
}
}
If you have a helper to generate, iterate and populate an int[,] matrix like this one:
public class VisitMatrix{
public static int[,] execute(int rows, int columns, Func<int, int, int> fn)
{
int[,] result = new int[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = fn(i, j);
}
}
return result;
}
}
Now matrix multiplication is as trivial as doing (supposing m1.GetLength(1) == m2.GetLength(0)):
public class MultiplyMatrices{
public static int[,] execute(int[,] m1, int[,] m2, int modulus = 10)
{
return VisitMatrix.execute(m1.GetLength(0), m2.GetLength(1), (i, j) =>
Enumerable.Range(0, m1.GetLength(1)-1)
.Select(k => m1[i, k] * m2[k, j])
.Aggregate(0, (a, b) => a + b, e => e % modulus)
}
}
I have an 8 X 8 matrix. Now, The below coordinates are occupied
{ 6, 3 }, { 5, 5 }, { 3, 3 }.... What needs to be done is that, I need to build straight line
through these points and needs to count how many coordinates they have touched?
My program so far stands as
private static void GetCount(int[,] Positions)
{
int rcount = 8;
int firstRow = Positions[0, 0];
for (int i = 1; i < Positions.Length/2; i++)
{
int currentRow = Positions[i, 0];
if (currentRow != firstRow)
{
rcount += 8;
firstRow = currentRow;
}
}
int cCount = 8;
int firstCol = Positions[0, 1];
for (int i = 1; i < Positions.Length / 2; i++)
{
int currentCol = Positions[i, 1];
if (currentCol != firstCol)
{
cCount += 8;
firstCol = currentCol;
}
}
int totalCount = rcount - cCount;
Console.WriteLine(totalCount);
}
And I am invoking it as
GetCount(new int[,] { { 6, 3 }, { 5, 5 }, { 3, 3 } });
The output will be 40 here. (count will be 24 for each 3 unique rows i.e. 6,5,3 and count will be 16 for 2 unique columns i.e. 3 and 5... So, the total count is 24+16 = 40)
But I am getting the output as 48.
Also is it possible to do the porgram using one single loop?
I am using C# 1.0
Edited
This does work
List<int> lstRows = new List<int>();
List<int> lstCols = new List<int>();
int count = 0;
//Get the unique rows and columns
for (int i = 0; i < marinePositions.Length / 2; i++)
{
if (!lstRows.Contains(marinePositions[i, 0])) lstRows.Add(Positions[i, 0]);
if (!lstCols.Contains(marinePositions[i, 1])) lstCols.Add(Positions[i, 1]);
}
//get row count
for (int i = 0; i < lstRows.Count; i++) count += 8;
//get column count
for (int i = 0; i < lstCols.Count; i++) count += 8;
Console.WriteLine(count);
But need a much better one.. if possible using linq/lambda and no loop
Please help
Here u go... but this in is LINQ and not C# 1.0 which is way too old.. not sure why are you using such old version of the language:
private static void GetCount(int[,] Positions)
{
List<int> x = new List<int>();
List<int> y = new List<int>();
for (int i = 0; i < Positions.Length/2; i++)
{
x.Add(Positions[i, 0]);
y.Add(Positions[i, 1]);
}
int result = (x.Distinct().Count() * 8) + (y.Distinct().Count() * 8);
Console.WriteLine(result);
}
No loops magic:
private static void GetCount(int[,] Positions)
{
var range = Enumerable.Range(0, Positions.Length / 2);
var result = (range.Select(i => Positions[i, 0]).Distinct().Count() * 8) +
(range.Select(i => Positions[i, 1]).Distinct().Count() * 8);
Console.WriteLine(result);
}
CORRECTIONS:
1-
int cCount = 8;
To:
int cCount = 0;
2-
int totalCount = rcount - cCount;
To:
int totalCount = rcount + cCount;
The program should work fine now.