enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testing_random
{
class Program
{
static void Main(string[] args)
{
int n = 4;
int[,] a = new int[n,n];//declaring the matrix
Random o = new Random();
a[0,0] = o.Next(n);
for (int i = 1; i < n; i++)//filling the first line
{
int d = 1;
while (d != 0)
{
a[i,0] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i,0] == a[j,0])
d++;
}
}
for (int i = 1; i < n; i++)//filing the first column
{
int d = 1;
while (d != 0)
{
a[0, i] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[0, i] == a[0, j])
d++;
}
}
for (int k = 1; k < n; k++)//filling the rest of the matrix
for (int i = 1; i < n; i++)
{
int d = 1;
while (d != 0)
{
a[i, k] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i, k] == a[j, k])
d++;
for (int j = 0; j < k; j++)
if (a[i, k] == a[i, j])
d++;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write("{0} ", a[i, j]);
Console.WriteLine();
}
Console.ReadLine();
}
}
}
The output should be a matrix of 4*4 where each column and each line contains each number once.
The problem is when i run the code, not every time i get an output, i think the problem is not every set of first line and column can give a matrix as required the i get into an unending loop.
what i want to do is limit the running time of the application to 100 ms per example,so if the matrix is not filled,the program restarts
What piece of code am i missing?
replace the while( d != 0 ) with a loop which counts up to a certain very large maximum number of iterations. (Try 1000, 100000, whatever.)
Are you trying to randomly insert numbers between 1-4 in the first line of the array? If so there is a much easier way to do it.
You can generate the 4 numbers to be inserted into the array and then just look through the first line of the array and set each value.
Random rnd = new Random();
var randomNumbers = Enumerable.Range(1, 4).OrderBy(i => rnd.Next()).ToArray();
for (int i = 0; i < n; i++)
{
a[i, 0] = randomNumbers[i];
}
Related
As you can see this is 2D transpose of matrix program, when executing this program it throws an index out of bound exception when it reached in some lines of code. Code raising exception is mentioned below.
C# Program
static void Main(string[] args)
{
Console.Write("No of Rows entered = ");
int r = Convert.ToInt32(Console.ReadLine());
Console.Write("No of Columns entered = ");
int c= Convert.ToInt32(Console.ReadLine());
int[,] arr1 = new int[r, c];
int[,] arr2 = new int[r, c];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
Console.Write("[{0}],[{1}] : ", i, j+" ");
arr1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix before Transpose:");
for (int i = 0; i < r; i++)
{
Console.WriteLine();
for (int j = 0; j < c; j++)
Console.Write("{0}", arr1[i, j]+" ");
}
```
**When it execute this lines of code it shows exception**
```
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
arr2[j, i] = arr1[i, j];
}
}
Console.WriteLine("Matrix after Transpose: ");
for (int i = 0; i < r; i++)
{
Console.WriteLine();
for (int j = 0; j < c; j++)
{
Console.Write("{0}", arr2[i, j]);
}
}
}
```
[Image of Exception appear while executing the program][1]
[1]: https://i.stack.imgur.com/6rNCg.png
The position of r and c should be changed in the definition of arr2:
int[,] arr2 = new int[c, r];
In the last for-loop, r and c should also be changed from position:
Console.WriteLine("Matrix after Transpose: ");
for (int i = 0; i < c; i++)
{
Console.WriteLine();
for (int j = 0; j < r; j++)
{
Console.Write("{0}", arr2[i, j]);
}
}
at the beginning I want to mention that I am a beginner in programming. So, I want to write a program that checks the similarity of two-dimensional arrays of integers. The similarity is to be determined by the amount of numbers that are in the same positions in both tables. The user gives the number of columns in the table and the elements themselves, number of rows is the same all the time.The similarity result is displayed as a percentage and the similarity itself should be calculated taking into account the number of elements of the larger array. My problem is: When the two arrays are the same size, the program throws the exception and it doesn't check all the numbers in the column.(I wrote before program for one dimensional array and it works perfectly) So far I have managed to write something like this:
This is what I want to do In the picture, the similarity between the arrays is 20%
{
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int z = 2;
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < z; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int rowLength = tab1.GetLength(0);
int colLength = tab1.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int b = 2;
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < b; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int Len4gth = tab2.GetLength(0);
int Len2gth = tab2.GetLength(1);
for (int i = 0; i < Len4gth; i++)
{
for (int j = 0; j < Len2gth; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
double similarity= 0;
if (tab1.GetLength(1) > tab2.GetLength(1))
{
for (int i = 0; i < tab2.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) < tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab2[i, j] == tab1[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) == tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.Length < tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
if (tab1.Length > tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab1.Length) * 100 + "%");
}
if (tab1.Length == tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
Console.ReadKey();
You must compare each element of the first array with the elements of the second array.
use this code :
//get first array items
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
//write first array items
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//get second array items
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
//write second array items
Console.WriteLine("\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//find similarity items
double similarity = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
int firstValue = tab1[i, j];
for (int k = 0; k < 2; k++)
{
for (int d = 0; d < m; d++)
{
if (firstValue == tab2[k, d])
{
similarity += 1;
}
}
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();
this code work without error and It does not matter which array is larger.
If you want similar elements like this example enter link description here, use this code snippet to find similar elements
//find similarity items
double similarity = 0;
int z = n > m ? m : n;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity += 1;
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();
I am making a program, where I need to calculate linear regression, but I got stuck at inversion of a matrix.
I have
double[,] location = new double[3,3];
It was then filled with numbers, but then I do not know, how to count the inverse matrix for it like in Linear algebra.
I searched for a solution on the internet, but there was some Matrix class that I dont know how to convert my double[,] to.
So, do you know some elegant way to inverse double[,] like the inversion of matrixes in Linear algebra?
Here you have a working example, just copy the entire code into a console project and run it.
I took it from this link https://jamesmccaffrey.wordpress.com/2015/03/06/inverting-a-matrix-using-c/
using System;
using System.Collections.Generic;
using System.Linq;
namespace matrixExample
{
class Program
{
static void Main(string[] args)
{
double[][] m = new double[][] { new double[] { 7, 2, 1 }, new double[] { 0, 3, -1 }, new double[] { -3, 4, 2 } };
double[][] inv = MatrixInverse(m);
//printing the inverse
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
Console.Write(Math.Round(inv[i][j], 1).ToString().PadLeft(5, ' ') + "|");
Console.WriteLine();
}
}
static double[][] MatrixCreate(int rows, int cols)
{
double[][] result = new double[rows][];
for (int i = 0; i < rows; ++i)
result[i] = new double[cols];
return result;
}
static double[][] MatrixIdentity(int n)
{
// return an n x n Identity matrix
double[][] result = MatrixCreate(n, n);
for (int i = 0; i < n; ++i)
result[i][i] = 1.0;
return result;
}
static double[][] MatrixProduct(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) // could use k less-than bRows
result[i][j] += matrixA[i][k] * matrixB[k][j];
return result;
}
static double[][] MatrixInverse(double[][] matrix)
{
int n = matrix.Length;
double[][] result = MatrixDuplicate(matrix);
int[] perm;
int toggle;
double[][] lum = MatrixDecompose(matrix, out perm,
out toggle);
if (lum == null)
throw new Exception("Unable to compute inverse");
double[] b = new double[n];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (i == perm[j])
b[j] = 1.0;
else
b[j] = 0.0;
}
double[] x = HelperSolve(lum, b);
for (int j = 0; j < n; ++j)
result[j][i] = x[j];
}
return result;
}
static double[][] MatrixDuplicate(double[][] matrix)
{
// allocates/creates a duplicate of a matrix.
double[][] result = MatrixCreate(matrix.Length, matrix[0].Length);
for (int i = 0; i < matrix.Length; ++i) // copy the values
for (int j = 0; j < matrix[i].Length; ++j)
result[i][j] = matrix[i][j];
return result;
}
static double[] HelperSolve(double[][] luMatrix, double[] b)
{
// before calling this helper, permute b using the perm array
// from MatrixDecompose that generated luMatrix
int n = luMatrix.Length;
double[] x = new double[n];
b.CopyTo(x, 0);
for (int i = 1; i < n; ++i)
{
double sum = x[i];
for (int j = 0; j < i; ++j)
sum -= luMatrix[i][j] * x[j];
x[i] = sum;
}
x[n - 1] /= luMatrix[n - 1][n - 1];
for (int i = n - 2; i >= 0; --i)
{
double sum = x[i];
for (int j = i + 1; j < n; ++j)
sum -= luMatrix[i][j] * x[j];
x[i] = sum / luMatrix[i][i];
}
return x;
}
static double[][] MatrixDecompose(double[][] matrix, out int[] perm, out int toggle)
{
// Doolittle LUP decomposition with partial pivoting.
// rerturns: result is L (with 1s on diagonal) and U;
// perm holds row permutations; toggle is +1 or -1 (even or odd)
int rows = matrix.Length;
int cols = matrix[0].Length; // assume square
if (rows != cols)
throw new Exception("Attempt to decompose a non-square m");
int n = rows; // convenience
double[][] result = MatrixDuplicate(matrix);
perm = new int[n]; // set up row permutation result
for (int i = 0; i < n; ++i) { perm[i] = i; }
toggle = 1; // toggle tracks row swaps.
// +1 -greater-than even, -1 -greater-than odd. used by MatrixDeterminant
for (int j = 0; j < n - 1; ++j) // each column
{
double colMax = Math.Abs(result[j][j]); // find largest val in col
int pRow = j;
//for (int i = j + 1; i less-than n; ++i)
//{
// if (result[i][j] greater-than colMax)
// {
// colMax = result[i][j];
// pRow = i;
// }
//}
// reader Matt V needed this:
for (int i = j + 1; i < n; ++i)
{
if (Math.Abs(result[i][j]) > colMax)
{
colMax = Math.Abs(result[i][j]);
pRow = i;
}
}
// Not sure if this approach is needed always, or not.
if (pRow != j) // if largest value not on pivot, swap rows
{
double[] rowPtr = result[pRow];
result[pRow] = result[j];
result[j] = rowPtr;
int tmp = perm[pRow]; // and swap perm info
perm[pRow] = perm[j];
perm[j] = tmp;
toggle = -toggle; // adjust the row-swap toggle
}
// --------------------------------------------------
// This part added later (not in original)
// and replaces the 'return null' below.
// if there is a 0 on the diagonal, find a good row
// from i = j+1 down that doesn't have
// a 0 in column j, and swap that good row with row j
// --------------------------------------------------
if (result[j][j] == 0.0)
{
// find a good row to swap
int goodRow = -1;
for (int row = j + 1; row < n; ++row)
{
if (result[row][j] != 0.0)
goodRow = row;
}
if (goodRow == -1)
throw new Exception("Cannot use Doolittle's method");
// swap rows so 0.0 no longer on diagonal
double[] rowPtr = result[goodRow];
result[goodRow] = result[j];
result[j] = rowPtr;
int tmp = perm[goodRow]; // and swap perm info
perm[goodRow] = perm[j];
perm[j] = tmp;
toggle = -toggle; // adjust the row-swap toggle
}
// --------------------------------------------------
// if diagonal after swap is zero . .
//if (Math.Abs(result[j][j]) less-than 1.0E-20)
// return null; // consider a throw
for (int i = j + 1; i < n; ++i)
{
result[i][j] /= result[j][j];
for (int k = j + 1; k < n; ++k)
{
result[i][k] -= result[i][j] * result[j][k];
}
}
} // main j column loop
return result;
}
}
}
I guess this is what you are looking for:
static double[][] MatrixInverse(double[][] matrix)
{
// assumes determinant is not 0
// that is, the matrix does have an inverse
int n = matrix.Length;
double[][] result = MatrixCreate(n, n); // make a copy of matrix
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
result[i][j] = matrix[i][j];
double[][] lum; // combined lower & upper
int[] perm;
int toggle;
toggle = MatrixDecompose(matrix, out lum, out perm);
double[] b = new double[n];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
if (i == perm[j])
b[j] = 1.0;
else
b[j] = 0.0;
double[] x = Helper(lum, b); //
for (int j = 0; j < n; ++j)
result[j][i] = x[j];
}
return result;
}
See Test Run - Matrix Inversion Using C# for reference.
The following code sorts rows by the first element using bubble method.
I can't change it to counting sort.
public void SortStack(double[,] n)
{
for (int i = 0; i < n.GetLength(0) - 1; i++)
{
for (int j = i; j < n.GetLength(0); j++)
{
if (n[i, 0] > n[j, 0])
{
for (int k = 0; k < n.GetLength(1); k++)
{
var temp = n[i, k];
n[i, k] = n[j, k];
n[j, k] = temp;
}
}
}
}
}
Please help.
As you do bubble sort based on first element of each row. you should do counting sort like that too. so you just need to count first item of each row.
private static int[,] CountingSort2D(int[,] arr)
{
// find the max number by first item of each row
int max = arr[0, 0];
for (int i = 0; i < arr.GetLength(0); i++)
{
if (arr[i, 0] > max) max = arr[i, 0];
}
// we want to get count of first items of each row. thus we need 1d array.
int[] counts = new int[max + 1];
// do the counting. again on first index of each row
for (int i = 0; i < arr.GetLength(0); i++)
{
counts[arr[i, 0]]++;
}
for (int i = 1; i < counts.Length; i++)
{
counts[i] += counts[i - 1];
}
// result is sorted array
int[,] result = new int[arr.GetLength(0), arr.GetLength(1)];
for (int i = arr.GetLength(0) - 1; i >= 0; i--)
{
counts[arr[i, 0]]--;
// now we need to copy columns too. thus we need another loop
for (int j = 0; j < arr.GetLength(1); j++)
{
result[counts[arr[i, 0]], j] = arr[i, j];
}
}
return result;
}
Here is the test.
static void Main()
{
Random rand = new Random();
int[,] arr = new int[3,3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i, j] = rand.Next(0, 100);
}
}
int[,] newarr = CountingSort2D(arr);
for (int i = 0; i < arr.GetLength(0); i++)
{
Console.Write("{ ");
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ,");
}
Console.Write("} ,");
}
Console.WriteLine();
for (int i = 0; i < newarr.GetLength(0); i++)
{
Console.Write("{ ");
for (int j = 0; j < newarr.GetLength(1); j++)
{
Console.Write(newarr[i, j] + " ,");
}
Console.Write("} ,");
}
Console.WriteLine();
}
Example Output:
{ 49,66,8 },{ 33,39,64 },{ 65,52,76 } // Original array
{ 33,39,64 },{ 49,66,8 },{ 65,52,76 } // Sorted array
I am trying to learn two dimensional array and I wrote some basic code, but I am getting this exception. Could you tell me what am I doing wrong?
static void Main(string[] args)
{
Random rnd = new Random();
int[,] array = new int[2, 2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; i++)
{
array[i, j] = rnd.Next(0, 100);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
Console.WriteLine(array[i, 0] + "---" + array[i, 1]);
}
Console.ReadLine();
}
The problem is in your inner for-loop. In the iterator section, you're incrementing the i variable, but it should be j. Try this:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
array[i, j] = rnd.Next(0, 100);
}
}