I have to write a program that finds the difference between the sums of square matrix diagonals for homework, but my code throws IndexOutOFRange exception and I have no idea how to fix it.
Source code below:
//input 3 11 2 4 4 5 6 10 8 -12 //desired output: 15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class diagonalDifference
{
static void Main()
{
int N = Convert.ToInt16(Console.ReadLine());
int[,] arr = new int[N, N];
string str = string.Empty;
for (int i = 0; i < N; ++i)
{
string[] strArr = Console.ReadLine().Split(' ');
for (int j = 0; j < strArr.Length; ++j)
{
arr[i, j] = Convert.ToInt16(strArr[j]);
}
}
int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
while (left <= right)
{
ldTotal += arr[left, left];
rdTotal += arr[left++, right];
}
Console.WriteLine(Math.Abs(ldTotal - rdTotal));
}
}
class diagonalDifference
{
static void Main()
{
int N = Convert.ToInt16(Console.ReadLine());
int[,] arr = new int[N, N];
string str = string.Empty;
for (int i = 0; i < N; ++i)
{
string[] strArr = Console.ReadLine().Split(' ');
for (int j = 0; j < strArr.Length; ++j)
{
arr[i, j] = Convert.ToInt16(strArr[j]);
}
}
int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
while (left <= (N-1))
{
ldTotal += arr[left, left];
rdTotal += arr[left, right];
Left++;
Right--;
}
Console.WriteLine(Math.Abs(ldTotal - rdTotal));
}
}
class Result
{
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
public static int diagonalDifference(List<List<int>> arr)
{
int l=arr.Count;
int d1=0;
int d2=0;
for(int i=0;i<l;i++)
{
d1=d1+arr[i][i];
d2=d2+arr[i][l-1-i];
}
return (Math.Abs(d1-d2));
}
}
Related
Hello everyone I am new to programming in c#, what I am going to do is that I want to convert the 2D string array to 2D integer array, the reason for this conversion is that I want to pass that integer array to another method for some calculation. Thanks in advance for helping.
public void Matrix()
{
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
Random rnd = new Random();
int[,] matrixA = new int[a, b];
string matrixString = "";
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
matrixString += matrixA[i, j];
matrixString += " ";
}
matrixString += Environment.NewLine;
}
txtA.Text = matrixString;
txtA.TextAlign = HorizontalAlignment.Center;
}
Your code is actually pretty close. Try this:
private Random rnd = new Random();
public int[,] Matrix(int a, int b)
{
int[,] matrixA = new int[a, b];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
}
}
return matrixA;
}
What you have there is a function that does not rely on any WinForms controls and will produce your int[,] quickly and efficiently.
Let the calling code work with the WinForms controls:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
Now you can pass the matrix to anything that requires an int[,].
If you need to display the matrix then create a separate function for that:
public string MatrixToString(int[,] matrix)
{
StringBuilder sb = new();
for (int i = 0; i < matrix.GetLength(0); i++)
{
string line = "";
for (int j = 0; j < matrix.GetLength(1); j++)
{
line += $"{matrix[i, j]} ";
}
sb.AppendLine(line.Trim());
}
return sb.ToString();
}
Your calling code would look like this:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
UseTheMatrix(matrix);
txtA.Text = MatrixToString(matrix);
txtA.TextAlign = HorizontalAlignment.Center;
A sample run produces:
You can use List as a helper to store the elements of the array extracted from the string, but first I replaced the SPACE between elements in your string with a special character '|' as a separator to make it easier to extract the numbers from the string.
you can do somthing like this:
public static int[,] ConvertToInt(string matrix)
{
List<List<int>> initial = new List<List<int>>();
int lineNumber = 0;
int currenctIndex = 0;
int lastIndex = 0;
int digitCount = 0;
initial.Add(new List<int>());
foreach (char myChar in matrix.ToCharArray())
{
if (myChar == '|')
{
initial[lineNumber].Add(int.Parse(matrix.Substring(lastIndex, digitCount)));
lastIndex = currenctIndex+1;
digitCount = 0;
}
else
digitCount++;
if (myChar == '\n')
{
lineNumber++;
if(currenctIndex < matrix.Length-1)
initial.Add(new List<int>());
}
currenctIndex++;
}
int[,] myInt = new int[initial.Count, initial[0].Count];
for (int i = 0; i < initial.Count; i++)
for (int j = 0; j < initial[i].Count; j++)
myInt[i, j] = initial[i][j];
return myInt;
}
A sequence of n points in three-dimensional space is given.
It is necessary to find such an even permutation of its indices
that after its application the sequence becomes good.
Here is a link to the solution of this problem:
https://studwork.org/away?href=https%3A%2F%2Fhabr.com%2Fru%2Fcompany%2Fyandex%2Fblog%2F340784%2F%23%3A~%3Atext%3D%25D0%25BF%25D0%25B0%25D0%25BC%25D1%258F%25D1%2582%25D0%25B8%253A%2520256%2520%25D0%259C%25D0%2591-%2C%25D0%25A0%25D0%25B5%25D1%2588%25D0%25B5%25D0%25BD%25D0%25B8%25D0%25B5%2C-%25D0%2597%25D0%25B0%25D0%25B4%25D0%25B0%25D1%2587%25D1%2583%2520%25D0%25BC%25D0%25BE%25D0%25B6%25D0%25BD%25D0%25BE%2520%25D1%2580%25D0%25B5%25D1%2588%25D0%25B8%25D1%2582%25D1%258C
I wrote a program, but the answer is incorrect or the program is written incorrectly. Here is the program:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Journey_CSharp_5
{
class Program
{
private static void Main(string[] args)
{
List<List<int>> points;
int n;
using (StreamReader sr = new StreamReader("input.txt"))
{
n = int.Parse(sr.ReadLine());
points = new List<List<int>>(n);
for (int i = 0; i < n; i++)
{
String coords = sr.ReadLine();
string[] tokenscoord = coords?.Split(' ');
if (tokenscoord != null) points.Add(new List<int>
{
int.Parse(tokenscoord[0]),
int.Parse(tokenscoord[1]),
int.Parse(tokenscoord[2])
});
}
bool ok = Check(points);
int[] perm = { 0, 0, 0 };
Random rand = new Random();
while (!ok)
{
for (int j = 0; j < 3; j++) perm[j] = rand.Next() % n;
if (perm[0] == perm[1] || perm[0] == perm[2] || perm[1] == perm[2]) continue;
var points_copy = points;
var tmp = points_copy[perm[0]];
points_copy[perm[0]] = points_copy[perm[1]];
points_copy[perm[1]] = points_copy[perm[2]];
points_copy[perm[2]] = tmp;
ok = Check(points_copy);
}
List<int> ans = new List<int>();
for (int i = 0; i < n; i++) ans.Add(i);
int tmp1 = ans[perm[0]];
ans[perm[0]] = ans[perm[1]];
ans[perm[1]] = ans[perm[2]];
ans[perm[2]] = tmp1;
using (StreamWriter sw = new StreamWriter("output.txt"))
{
for (int i = 0; i < n; i++) sw.Write(ans[i] + 1);
}
}
}
private static long Vect(long xp, long yp, long xt, long yt)
{
return xp * yt - yp * xt;
}
private static bool CheckOrder(int i, int j, List<List<int>> points)
{
int[] signs = { 0, 0, 0 };
for (var k = 0; k < points.Count; k++)
{
int prv = (k - 1 + points.Count) % points.Count;
int cur = k;
int nxt = (k + 1) % points.Count;
long vres = Vect(
points[cur][(int)i] - points[prv][(int)i],
points[cur][(int)j] - points[prv][(int)j],
points[nxt][(int)i] - points[prv][(int)i],
points[nxt][(int)j] - points[prv][(int)j]);
switch (Math.Sign(vres))
{
case -1:
signs[0] += 1;
break;
case 0:
signs[1] += 1;
break;
case 1:
signs[2] += 1;
break;
}
}
return (signs[0] != 0 && signs[2] != 0) || (signs[1] != 0);
}
private static bool Check(List<List<int>> points)
{
List<Tuple<int, int>> ids = new List<Tuple<int, int>>
{
new Tuple<int, int>(0, 1),
new Tuple<int, int>(1, 2),
new Tuple<int, int>(0, 2)
};
bool ok = true;
for (int i = 0; i < 3; i++) ok &= CheckOrder(ids[i].Item1, ids[i].Item2, points);
return ok;
}
}
}
Verdict:
wrong-answer
I also rewrote this program in C# and get the compilation log:
stdout:
Compilation succeeded - 1 warning(s)
stderr:
warning CS8001: SDK path could not be resolved
Although only Mono C# 5.2.0 can be selected on this site.
Please tell me what is wrong with my program?
It is necessary to remove the directive using
System.Linq;
I am creating a 2D array that can have any custom size 1x1, 2x2, 3x3 .... nxn and depending on what the size of the array is, it gets filled with 0 to (n^2)-1, so if it is 2x2 it outputs:
3 2
1 0
It should be something like this int[,] arr = new int [n, n];, to create the 2d array, but how would the for loops be constructed?
what I have tried
using System;
namespace moveElement {
public class move {
static void Main(string[] args) {
int n = 3;
int[, ] arr = new int[n, n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
The result of the code:
0 0 0
0 0 0
0 0 0
int k = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i,j] = k++;
}
}
full code to the question:
using System;
namespace moveElement
{
public class move
{
static void Main(string[] args)
{
int n = 3;
int[,] arr = new int [n, n];
//Ivan Smyrnov solution
int k = (n * n) - 1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i,j] = k--;
}
}
//Ivan Smyrnov solution
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output when n is 3:
8 7 6
5 4 3
2 1 0
Okay I'm having a problem with the selection sort algorithm. It'll sort ints just fine but when I try to use it for doubles it starts to sort randomly.
here's my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sorter.ListSort;
using System.Collections;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
var x = new List<double>();
x.Add(23.1);
x.Add(1.5);
x.Add(3);
x.Add(15.23);
x.Add(101.2);
x.Add(23.35);
var sorted = selectionSort(x);
foreach (double s in sorted)
Console.WriteLine(s);
Console.ReadLine();
}
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
return data;
}
}
}
Now this is what the algorithm is returning
As we can see 3 is NOT bigger than 15.23, what's going on?
Like MoreON already mentioned in the comments, you should swap the elements after you've found the min value.
So it should look like this
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
}
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
return data;
}
But if you don't want to reinvent the wheel, you could also use:
var sorted = x.OrderBy(o => o).ToList();
You need to change place for int min
for (int i = 0; i < count - 1; i++)
{
for (int j = i + 1; j < count; j++)
{
int min = i;
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
Add a new method called swap and use the following selection sort code.
void swap(int *a,int*b){
int temp=*a;
*a=*b;
*b=temp;
}
void selectionSort(int arr[],int n){
int min_index;
for(int i=0;i<n-1;i++)
{
min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
min_index=j;
}
swap(&arr[min_index],&arr[i]);
}
}
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.