I was wondering how can I stop the iteration through the rows and columns of a 2d matrix if a value is found.
int[,] matrix = new int[8, 10];
Random rnd = new Random();
bool value = false;
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
int number = rnd.Next(1, matrix.Length + 1);
matrix[row, col] = number;
Console.Write("{0,3}", number);
if (number == 8)
{
value = true;
break;
}
}
}
Related
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();
}
I would like to have 4 list of data which are 12 randomly picked data on each row in those table with a designated pattern of "*".
I did try use Random() function but it was not working as the desire output.
Below are my sample code :
for (int i = 0; i < dgvA1.Rows.Count; i++)
{
int row = 0; int col = 0;
//Get First Row
for (int x = 0; x < 12;x++)
{
Random r = new Random();
int randomNumber = r.Next(1, 35); //for ints
row = randomNumber;
col = randomNumber;
rbLog.Text += row.ToString() + ";" + col.ToString();
}
}
Below are the picture of the table, and the red line are the coordinate that i wanted to be randomly selected on each of the line.
Total will be 4 line of random picked with 12 data each line. Any other method or linQ can done that?
Thanks
Here's some code to get you started -
List<(int, int)> principalDiagonalIndices = new List<(int, int)>();
List<(int, int)> secondaryDiagonalIndices = new List<(int, int)>();
int rowCount = dgvA1.Rows.Count;
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
if (i == j)
{
principalDiagonal.Add((i, j));
}
else if ((i + j) == (rowCount - 1))
{
secondaryDiagonalIndices.Add((i, j));
}
}
}
Random r = new Random();
for (int i = 0; i < 12; i++)
{
var principalIdx = principalDiagonalIndices[r.Next(0, principalDiagonalIndices.Count)];
Console.WriteLine("Random principal diagonal index - {0}", dgvA1[principalIdx.Item1, principalIdx.Item2]);
var secondaryIdx = secondaryDiagonalIndices[r.Next(0, secondaryDiagonalIndices.Count)];
Console.WriteLine("Random secondary diagonal index - {0}", dgvA1[secondaryIdx.Item1, secondaryIdx.Item2]);
}
Collect the principal and secondary diagonal in the list and iterate 12 times to get a pseudo-random index.
For principal diagonal, if you observe the row and column are equal (i == j).
And for secondary diagonal it should be row and col index summed up should equal to one minus the row-count.
Hi I am very new to coding and was trying to figure out how to create a 2d array. That asks the user to input row and column size than fills those chosen row and column sizes with random numbers. After days of trying to figure it out I decided to come on here for help. Here is what I have so far, its all over the places I KNOW.
char row = 'i';
char column = 'j';
int[,] twoDarray = new int[row, column];
int min = 0;
int max = 100;
Random randNum = new Random();
for (int i = 0; i < twoDarray.Length; ++i)
for (int j = 0; j < twoDarray.Length; ++j)
{
twoDarray[i, j] = Convert.ToInt32(In.ReadLine());
}
Not sure if I understand your question. I will assume that it is a console application. In that case, the code could look like:
int row, column;
string rowVal;
Console.Write("\nEnter Number of Rows: ");
rowVal = Console.ReadLine();
string colVal;
Console.Write("\nEnter Number of Columns: ");
colVal = Console.ReadLine();
bool allGood = true;
if(!int.TryParse(rowVal, out row))
{
allGood = false;
Console.Write("Number of Rows is wrong: ");
}
if (!int.TryParse(colVal, out column))
{
allGood = false;
Console.Write("Number of Columns is wrong: ");
}
if (!allGood)
throw new Exception("Wrong input data"); //or just return from your method
int[,] twoDarray = new int[row, column];
int min = 0;
int max = 100;
Random randNum = new Random();
for (int i = 0; i < twoDarray.GetLength(0); ++i)
{
for (int j = 0; j < twoDarray.GetLength(1); ++j)
{
twoDarray[i, j] = randNum.Next(min,max);
}
}
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();
}
}
}
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.