I am working on a C# program that has to copy the elements of a randomized 10*12 2D array on a 1D Array. Everything seems to be working fine. However, some of the elements of the 2D Array (last 18) would not copy to the 1D Array.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace James_Archbold_A1
{
class Program
{
static void Main(string[] args)
{
int row = 10;
int column = 12;
int[,] twoDArray = new int[row, column];
int[] oneDArray = new int[row*column];
FillTwoDimArray(twoDArray);
DisplayTwoDimArray(twoDArray);
StoreValues(twoDArray, oneDArray);
DisplayOneDimArray(oneDArray);
Console.ReadLine();
}
static void FillTwoDimArray(int[,] table)
{
int min = 0;
int max = 100;
int rndNumber;
Random rnd = new Random();
for (int row = 0; row < table.GetLength(0); row++) //use GetLength(0) to get the size of the row
{
for (int col = 0; col < table.GetLength(1); col++) //use GetLength(1) to get the size of the column
{
rndNumber = rnd.Next(min,max);
table[row, col] = rndNumber;
}
}
}
static void DisplayTwoDimArray(int[,] table)
{
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write("{0}\t", table[row, col]);
}
}
Console.WriteLine();
}
static void StoreValues(int[,] twoDArray, int[] oneDArray)
{
int rowSize = twoDArray.GetLength(0);
int colSize = twoDArray.GetLength(1);
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
{
int element;
element = twoDArray[row, col];
oneDArray[row * rowSize + col] = element;
}
}
}
static void DisplayOneDimArray(int[] oneDArray)
{
for (int i = 0; i < oneDArray.GetLength(0); i++ )
{
Console.Write("{0}\t", oneDArray[i] );
}
Console.WriteLine();
}
}
}
If you have a 2x5 array, your rowSize is 2, and your colSize is 5. Then your loop is setting a value into the array at [row * rowSize + col]. The first few values of this will be:
0*2+0 = 0
0*2+1 = 1
0*2+2 = 2
0*2+3 = 3
0*2+4 = 4
1*2+0 = 2
1*2+1 = 3
1*2+2 = 4
1*2+3 = 5
So you are looping over the same values, setting them multiple times, and also not setting the last values in the array. If you have more rows than columns, I imagine you would get an out of bounds exception?
If you change row * rowSize + col to the correct mapping row * colSize + col, it should work.
Try following code to copy to 1D:
void StoreValues(int[,] twoDArray, int[] oneDArray)
{
int rowSize = twoDArray.GetLength(0);
int colSize = twoDArray.GetLength(1);
var total=rowSize*colSize;//TOTAL ITEMS IN 1D ARRAY
for (int row = 0, d=0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
{
//STORE AT POSITION d
oneDArray[d++] = twoDArray[row, col];
}
}
}
using row * rowSize + col will cause issue as explained in this answer.
Related
The following code calculate the sum of each row of 'int[,] a'. What I want is to modify it so it calculates the sum per column; 1+1+1, 2+2+2, 3+3+3, 4+4+4 instead of per row. These values will be put inside 'int[] output'
static void Main(string[] args)
{
int[,] a = {{ 1, 2, 3, 4},
{ 1, 2, 3, 4},
{ 1, 2, 3, 4} };
int[] b = SumColumn(a);
}
public static int[] SumColumn(int[,] a)
{
int[] output = new int[a.GetLength(1)];
int sum = 0;
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < a.GetLength(1); j++)
{
sum += a[i, j];
}
output[i] = sum;
sum = 0;
}
return output;
}
So i tried adding a counter and using a boolean in the nested loop (and otther methods), however it did not work for me.
Just swap i and j loops so you will iterate through columns first and then iterate for each row's j-th element in the column:
public static int[] SumColumn(int[,] a)
{
int[] output = new int[a.GetLength(1)];
int sum = 0;
for (int j = 0; j < a.GetLength(1); j++)
{
for (int i = 0; i < a.GetLength(0); i++)
{
sum += a[i, j];
}
output[j] = sum;
sum = 0;
}
return output;
}
This function initializes the output array with length equal to the number of columns in the input array. Then it declares an integer variable sum to accumulate a result for column.
Then we use two nested for loops to iterate over the rows and columns but use j and GetLength(1) in the outer loop to iterate via each column and i and GetLength(1) in the inner loop to iterate for each j-th element for all rows. Each iteration of the inner loop add value of the current cell to the sum.
After summarizing values in all rows we add the sum to the current index of the output and reset it for using in the next column.
The code is almost identical in both cases. Only the loops get flipped
static void Main(string[] args)
{
int[,] a = {{ 1, 2, 3, 4},
{ 1, 2, 3, 4},
{ 1, 2, 3, 4} };
int[] rowSums = RowSums(a);
int[] colSums = ColumnSums(a);
Console.WriteLine($"Row Sums: {string.Join(",", rowSums)}");
Console.WriteLine($"Col Sums: {string.Join(",", colSums)}");
}
public static int[] ColumnSums(int[,] matrix)
{
int rowCount = matrix.GetLength(0);
int colCount = matrix.GetLength(1);
int[] result = new int[colCount];
for (int j = 0; j < colCount; j++)
{
int sum = 0;
for (int i = 0; i < rowCount; i++)
{
sum += matrix[i, j];
}
result[j] = sum;
}
return result;
}
public static int[] RowSums(int[,] matrix)
{
int rowCount = matrix.GetLength(0);
int colCount = matrix.GetLength(1);
int[] result = new int[rowCount];
for (int i = 0; i < rowCount; i++)
{
int sum = 0;
for (int j = 0; j < colCount; j++)
{
sum += matrix[i, j];
}
result[i] = sum;
}
return result;
}
PS. In your code there is no need to set sum=0; in the end of the outer loop, as it will get set to zero in the beginning of the next loop.
The output should be
Row Sums: 10,10,10
Col Sums: 3,6,9,12
Something like this:
public static int[] SumColumn(int[,] array) {
// Do not forget to validate public method arguments
if (array is null)
return null;
// result is an array (an item for each column)
// Note, that result will be filled by 0, so we don't have to use sum variable
int[] result = new int[array.GetLength(1)];
// For each column col
for (int col = 0; col < result.Length; ++col)
for (int row = 0; row < array.GetLength(0); ++row) // ... we sum rows
result[col] += array[row][col];
return result;
}
i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}
Like the question says, I am trying to take the array listed below and go through each number, double the number, and return the new number to the array, and when it's all done, call the method to print the new array. My initial thoughts were that maybe I could go through by row/column and get the number that way, multiply by 2, and then return it, but I'm being told something along the lines of int can't be converted to int[,]. I can not seem to figure out where to go from here.
int[,] array_2d = {{1, 2, 3},{ 4, 5, 6},{7, 8, 9}};
public static int[ , ] DoubleArray(int[ , ] array_2d){
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col ++){
int val = array_2d[row,col];
return val * 2;
}
}
}
Also to clarify, The array is in the main method while this is a separate method needing to be called in the main with the array as the parameter.
Thanks in advance!
The reason for your int-related error is that you state your return type as 'int[,]' and then in your return statement, you are attempting to return a value of type 'int'. In order to fix this, you need to return a 2d int array as specified by your return type. I would also recommend fetching the length of the array dynamically instead of hardcoding in the three. The below code should do the job.
public static int[,] DoubleArray(int[,] array_2d)
{
for (int row = 0; row < array_2d.GetLength(0); row++)
{
for (int col = 0; col < array_2d.GetLength(1); col++)
{
int val = array_2d[row, col];
array_2d[row, col] = val * 2;
}
}
}
return array_2d;
}
EDIT: As #hijinxbassist pointed out, this will modify the original array, if instead you would like to keep the value of the original, you can use the slightly altered function below.
public static int[,] DoubleArray(int[,] array_2d)
{
int[,] newArray = (int[,])array_2d.Clone();
for (int row = 0; row < newArray.GetLength(0); row++)
{
for (int col = 0; col < newArray.GetLength(1); col++)
{
int val = newArray[row, col];
newArray[row, col] = val * 2;
}
}
}
return newArray;
}
i think you can do something like that:
public static int[,] DoubleArray(int[,] array_2d)
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
array_2d[row, col] = array_2d[row, col] * 2;
}
}
return array_2d;
}
public static void PrintArray(int[,] array_2d)
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
Console.Write($"{array_2d[row, col]} ");
}
}
}
public static void Main(string[] args)
{
int[,] array_2d = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
var doubledArray = DoubleArray(array_2d);
PrintArray(doubledArray);
}
I've been toying with this code which prints a small matrix with negative and positive numbers,
I would like an efficient way to add together only the positive elements on the matrix and get the product of such elements also do the same but after a specific number, such as the highest on the matrix
static void Main(string[] args)
{
int row = 5;
int column = 5;
int[,] array = new int[row, column];
Random rand = new Random();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
array[i, j] = rand.Next(-5, 10);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(array[i, j].ToString() + " ");
}
Console.WriteLine(" ");
}
Console.ReadLine();
}
To filter and add positive matrix elements, you could do something like the following:
static void Main(string[] args)
{
const int rows = 5;
const int columns = 5;
var array = new int[rows, columns];
var rand = new Random();
int sum = 0;
bool numberSeen = false;
int numberToSee = 1;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
var cell = rand.Next(-5, 10);
if (!numberSeen && (cell == numberToSee))
{
numberSeen = true;
}
array[row, col] = cell;
if (numberSeen && (cell > 0))
{
sum += cell;
}
}
}
Console.WriteLine($"sum = {sum}");
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Console.Write(array[row, col].ToString() + " ");
}
Console.WriteLine(" ");
}
Console.ReadLine();
}
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();
}
}
}