How to write recursive function for nested loops in C# - c#

How can I write recursive function for this for loops I am making sum of this array elements.
int[,,,] exampleArray = new int[1,2,3,4];
int sum = 0;
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 4; l++)
{
sum += exampleArray[i, j, k, l];
}
}
}
}
Console.WriteLine(sum);

it is actually quite simple, just need a way to represent all 4 indexes as single variable:
static int recursiveSum(int[,,,] a, int index = 0)
{
int ti = index;
int l = ti % a.GetLength(3); ti /= a.GetLength(3);
int k = ti % a.GetLength(2); ti /= a.GetLength(2);
int j = ti % a.GetLength(1); ti /= a.GetLength(1);
int i = ti % a.GetLength(0); ti /= a.GetLength(0);
if (ti > 0) {
return 0;
}
return a[i, j, k, l] + recursiveSum(a, index + 1);
}
static void Main(string[] args)
{
int[,,,] exampleArray = new int[1, 2, 3, 4];
int sum = recursiveSum(exampleArray);
Console.WriteLine(sum);
}

Related

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

How to invert double[,] in C#

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.

matrix, sub matrix with greatest sum

The task:
1. Make a matrix n by m and fill it with data from console.
2. Find the 3*3 sub matrix with the greatest sum.
{
static int[,] ArrayReadConsole()
{
Console.WriteLine("please enter n:");
int n;
n = Int32.Parse(Console.ReadLine());
Console.WriteLine("please enter m:");
int m;
m = Int32.Parse(Console.ReadLine());
int[,] data = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("please enter a new value");
int number;
number = Int32.Parse(Console.ReadLine());
data[i, j] = number;
}
}
return data;
}
static void SumOfPlatform(int[,] data)
{
int sum =0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum =+ data[i + k, j + l];
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum =0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}",maxSum,x,y );
}
static void Main()
{
int[,] data = ArrayReadConsole();
SumOfPlatform(data);
}
}
}
I wrote that code but something went wrong... It doesn't find position or sum of the matrix I enter. I know that 4x for loop is a bad idea just I didn't want to make another method just for that. Any idea why it doesn't work?
Your Code for SumOfPlatform is working with only change from =+ to +=
static void SumOfPlatform(int[,] data)
{
int sum = 0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum += data[i + k, j + l]; //only Change
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum = 0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}", maxSum, x, y);
}
static void Main(string[] args)
{
// int[,] data = ArrayReadConsole();
int[,] data = new int[,]
{
{1,4,6,7,3,5,7,4 },
{1,4,5,3,3,5,4,4 },
{1,1,6,2,1,5,7,4 },
{1,3,6,3,3,5,2,4 },
{1,4,6,2,3,5,3,4 },
{1,4,2,2,3,5,3,4 },
{1,4,3,3,3,5,2,4 },
{1,4,4,3,3,5,2,4 }
};
SumOfPlatform(data);
}

Displaying result of KMP compute prefix function

I'm trying to solve homework for school, it concerns KMP algorithm. Here is my compute prefix function, it is suppose to output a prefix table, however all it does is every time it returns all 0s. Could help me understand what am I doing wrong? Thanks!
static int[] computePrefixFunction(string P)
{
int m = P.Length;
int[] pi = new int[m];
pi[1] = 0;
int k = 0;
for (int j = 2; j < m; j++)
{
while (k > 0 && P[k + 1] != P[j])
{
k = pi[k];
}
if (P[k+1] == P[j])
{ k = k + 1; };
pi[j] = k;
}
for (int i = 0; i < pi.Length; i++)
{
Console.WriteLine(pi[i]);
}
return pi;
}
You a have messed up indexes offsets. Here is fixed version:
static int[] computePrefixFunction(string P)
{
int m = P.Length;
int[] pi = new int[m];
int k = 0;
for (int j = 1; j < m; j++)
{
k = pi[j - 1];
while (k > 0 && P[k] != P[j])
k = pi[k-1];
if (P[k] == P[j])
k = k + 1;
pi[j] = k;
}
return pi;
}
Live demo: https://dotnetfiddle.net/YQknMp

I am making a sudoku on c#

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];
}

Categories