How to delete a specific row and column from 2D array in C#?
int[,] array= {{1,2,3},{4,5,6},{7,8,9}};
lets say I want to delete row i and column i (skipping them) ... for nXn array not just 3x3 and store the remaining array in a new array...
so the output would be:
{5,6},{8,9}
There's no built-in way to do that, you can do it yourself:
static void Main()
{
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
var trim = TrimArray(0, 2, array);
}
public static int[,] TrimArray(int rowToRemove, int columnToRemove, int[,] originalArray)
{
int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1) - 1];
for (int i = 0, j = 0; i < originalArray.GetLength(0); i++)
{
if (i == rowToRemove)
continue;
for (int k = 0, u = 0; k < originalArray.GetLength(1); k++)
{
if (k == columnToRemove)
continue;
result[j, u] = originalArray[i, k];
u++;
}
j++;
}
return result;
}
No, arrays don't let you do that. You could make your own data structure for that, but it's not going to be exactly simple (unlike if you only wanted to be able to remove rows, for example).
For simple operations, it would be quite enough to build a class on top of an underlying array, and handle the re-indexing to map the virtual 2D array to the physical array underneath. But it's going to get a bit tricky as you combine removals and additions, and deform the array overall.
Very simple logic. Just play with the loop:
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] arrayskip = new int[array.GetLength(0) - 1, array.GetLength(1) - 1];
for (int i = 1; i < array.GetLength(0); i++)
{
for (int j = 1; j < array.GetLength(1); j++)
{
arrayskip[i - 1, j - 1] = array[i, j];
}
}
I created this method, have a look
public static double[,] fillNewArr(double[,] originalArr, int row, int col)
{
double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];
int newRow = 0;
int newCol = 0;
for (int i = 0; i < originalArr.GetLength(0); i++)
{
for (int j = 0; j < originalArr.GetLength(1); j++)
{
if(i != row && j != col)
{
tempArray[newRow, newCol] = originalArr[i, j];
newRow++;
newCol++;
}
}
}
return tempArray;
}
having some out of range, It's obvious why but I'm trying to get there...
Related
I have array with data. Array length equals 25 elements. I would like create matrix (5X5). How I can do this in C#? Please help.
Translating a single dimension array into a multi dimension array is straight forward.
public static T getEntry<T>(this T[] array, int column, int row, int width)
{
return array[column+row*width];
}
Add wrapper classes and/or validation as desired.
Usage example:
var array=Enumerable.Range(1,25).ToArray();
for (int row = 0; row < 5; row ++)
{
for (int column = 0; column < 5; column ++)
{
Console.WriteLine("Value in column {0}, row {1} is {2}", column, row, array.getEntry(column,row));
}
}
You can use Buffer.BlockCopy
using System;
class Test
{
static double[,] ConvertMatrix(double[] flat, int m, int n)
{
if (flat.Length != m * n)
{
throw new ArgumentException("Invalid length");
}
double[,] ret = new double[m, n];
// BlockCopy uses byte lengths: a double is 8 bytes
Buffer.BlockCopy(flat, 0, ret, 0, flat.Length * sizeof(double));
return ret;
}
static void Main()
{
double[] d = { 2, 5, 3, 5, 1, 6 };
double[,] matrix = ConvertMatrix(d, 3, 2);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]);
}
}
}
}
As #Taemyr suggest you can simply use indexing to simulate the structure of the matrix. If you need to access the element at row 2, col 3 in a 5 by 5 matrix simply access index 2*5+3 of your array. (row * # of cols + col)
If you want to split your array into a 2D array you can do so using the following code:
public static T[,] Matrix<T>(T[] arr, int rows) {
var cols = arr.Length / rows;
var m = new T[rows, cols];
for (var i = 0; i < arr.Length; i++)
m[i / cols, i % cols] = arr[i];
return m;
}
I am working on an issue where i need to Declare a two - dimensional array named multiplicationTable
that contains 4 elements by 4 elements.Initialize it in
a nested loop to contain elements that equal to the value
that is the product of the two index values for
each element. In a second nested loop, display the values
in the console output, with column elements separated with
commas, and row elements separated with carriage returns. This is what i have so far, for some reason can't wrap my brain around the solution! Any help would be appreciated!.
double[,] multiplicationTable = new double[4, 4];// { {1,2,3,4 }, {5,6,7,8 }, {9,10,11,12 }, {13,14,15,16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
Why not try to solve this with String.Join method? It is easy to use and will save you a lot of if-else statements. Here it is how it will look like with this method:
double[,] multiplicationTable = new double[4, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[4];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[multiplicationTable.GetLength(0)];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
I have a matrix, my mission is to fill 1D array from my matrix.
Example:
1 2 3
1 2 3
1 2 3
I need to sum the columns and fill the sum of every column in a 1D array
Here is my code (that doesn't work), (int[,] mat) is the matrix that the function gets.
public static int sumcolumn(int[,] mat)
{
int sum = 0;
int[] sumcol = new int[mat.GetLength(0)];
for (int y = 0; y < mat.GetLength(0); y++)
{
for (int i = 0; i < mat.GetLength(0); i++)
{
for (int j = 0; j < mat.GetLength(1); j++)
{
sum = sum + mat[j, i];
}
sumcol[i] = sum;
return sum;
sum = 0;
}
return sum;
}
return sumcol;
}
How should I do this mission?
Thanks in advance.
You need only 2 for loops. For each column run through all rows and sum up the content. Write the sum at the proper col index. Then after each column reset the sum. You also need to return the array with the sums. So I changed the return value:
Also it helps if you call the index variables with meaningful names.
public static int[] sumcolumn(int[,] mat)
{
int[] sumcol = new int[mat.GetLength(1)];
for (int col = 0; col < mat.GetLength(1); col++)
{
for (int row = 0; row < mat.GetLength(0); row++)
{
// since sumcol is initially filled with zeros you can just
// sum up the values from mat onto the zeros in each cell
sumcol[col] += mat[row, col];
}
}
return sumcol;
}
In the main you can test it like this:
void Main()
{
int[,] array = {
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },};
// this is just for test display
Console.WriteLine(String.Join(" ", sumcolumn(array)));
// normally you would call it like this and catch the return value in a new array
int[] result = sumcolumn(array);
}
So you need to evaluate a 2D matrix to get the column wise sum to a 1D array. So first thing you have to do is change the return type of the method to int[] instead for int.
Let me quote Few things that you have to notice before moving to a fix:
If you execute a return during iteration of the loop rest of iterations will not be executed.
A function can return only one value in a single call.
Let i and j be two positive unequal integers then a[i,j] and a[j,i] will points to two different elements in the matrix a.
As a whole you have to modify the method signature like the following:
public static int[] sumcolumn(int[,] mat)
{
int sum = 0;
int[] sumcol = new int[mat.GetLength(1)];
for (int i= 0; i< mat.GetLength(1); i++)
{
sum = 0; // reset sum for next colomn
for (int j= 0; j< mat.GetLength(0); j++)
{
sum += mat[i, j];
}
// iteration of column completed
sumcol[i] = sum;
}
return sumcol;
}
Linq approach
int[,] array = new int[3, 3] { { 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 } };
int[] result = Enumerable.Range(0, array.GetUpperBound(1) + 1)
.Select(y => Enumerable.Range(0, array.GetUpperBound(0) + 1)
.Select(x => array[x, y]).Sum()).ToArray(); // [3,6,9]
public static int[] sumColumn(int[,] mat)
{
//int sum = 0;
int colCount = mat.GetLength(0);
int[] sumCol = new int[colCount];
for (int y = 0; y < colCount; y++)
{
int rowCount = mat.GetLength(1);
sumCol[y] = 0;
for (int x = 0; x < rowCount; x++)
{
sumCol[y] += mat[y, x];
}
//sum += sumCol[y];
}
//return sum;
return sumCol;
}
sorry for noob question :). I've got 2d array 3x3 filled with random numbers (-5,5)
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
dPole[i, j] = nc.Next(-10, 10);
I want all the numbers that are positive and then save them into 1d array:
foreach (int j in dPole)
{
if (j > 0)
{
Console.WriteLine(j);
for (int i = 0; i < sizeOf1dArray; i++)
jPole[i] = j;
}
}
Output of Console.WriteLine(j)- to check if the condition is right:
6
2
5
6
9
8
Output of 1d Array:
8
8
8
8
8
8
Only the last number is saved into array. Why? Thanks.
An alternative route would be to use Cast<int> to flatten the array and use Where to filter.
int[,] dPole = new int[,] { { 3, -5, 0 }, { -3, 3, 2 }, { -2, 1, 1 } };
int[] jPole = dPole.Cast<int>().Where(i => i > 0).ToArray();
// jPole is now { 3, 3, 2, 1, 1 };
for (int i = 0; i < sizeOf1dArray; i++)
jPole[i] = j;
because at this loop action last j value is 8 and this loop fills all jPole array with j value every time, that means it fills all with 6 first, than puts 2 at entire array, then 5...... and for last it fills it with 8.
try something like that
int i = 0;
foreach (int j in dPole)
{
if (j > 0)
{
Console.WriteLine(j);
jPole[i] = j;
i++;
}
}
I've got the following arrays:
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
What I'd like to know how to do is:
Create a new array with the sum of myArray1 and myArray2
Create a new array with the subtraction of myArray1 and myArray2
Create a new array with the multiplication of myArray1 and myArray2
Result of sum would be:
int[,] myArray3 = new int[2, 3] { { 7, 6, 0 }, { -4, 4, 0 } };
Result of subtraction would be:
int[,] myArray3 = new int[2, 3] { { 5, 2, 6 }, { 12, 8, 16 } };
Result of multiplication would be:
int[,] myArray3 = new int[2, 3] { { 6, 8, 9 }, { 32, 12, 64 } };
Can this be done similar to printing out the arrays, with for loops? I tried looking for examples but found none that I could use for my specific problem.
int[,] a3 = new int[2,3];
for(int i = 0; i < myArray1.GetLength(0); i++)
{
for(int j = 0; j < myArray1.GetLength(1); j++)
{
a3[i,j] = myArray1[i,j] + myArray2[i,j];
a3[i,j] = myArray1[i,j] - myArray2[i,j];
a3[i,j] = myArray1[i,j] * myArray2[i,j];
}
}
need to store a3 before doing a new calculation obviously
For Sum:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray1[i, j] + myArray2[i, j];
}
}
For Subtraction:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray2[i, j] - myArray1[i, j];
}
}
For Multiplication:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = A[i, j] * B[i, j];
}
}
Yes this would be done exactly like printing out the arrays with for loops
c# has foreach loops which would be even easier to use
Note: I get the idea this is for homework so I'm not going to give a 100% conclusive end all be all answer.
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
foreach (int[] a1 in myArray1)
{
foreach(int i in a1)
{
//operation here
//you get the idea
}
}
If you want to do array manipulation faster use the C# Parallel.For loop from System.Threading.Tasks:
For simple arithmetic parallelizing the outer loop is much faster than not on a modern PC processor. For more complex operations, or for small array sizes, the parallel version can be slower for various reasons.
Thus, use a stopwatch to time your matrix operations, and use the fastest solution. Parallelization makes doing array / image processing in C# much faster if implemented right.
Beware of overflowing your datatypes after arithmetic operations and also sharing variables between multiple threads (see System.Threading.Interlocked for help with that)...
Subtraction below. Similar for addition and multiplication:
Parallel.For(0, array.GetLength(1), y=>
{
for (int x = 0; x < array.GetLength(0); x++)
{
difference[x,y] = minuend[x,y] - subtrahend[x,y];
}
}
});
If you want to use a for loop, you can iterate through the rows/columns of the multi-d array as follows:
for (int i = 0; i < myArray1.GetLength(0); i++)
{
for (int j = 0; j < myArray1.GetLength(1); j++)
{
// Here, you can access the array data by index, using i and j.
// Ex, myArray1[i, j] will give you the value of 1 in the first iteration.
}
}
Note: When you pass a value into the Array's GetLength method, it represents the dimension of the array. See http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx