[8, 8] I have a 2-dimensional array creating rows and columns [i, j].
I want to check if there is an object in a single row. For example, line 4 or line 1.
You can run a for lopp and check.
int i = 0; //or 3 //here you can set the row number
bool exists = false;
int value = 4;
for(int j = 0; j < array.GetLength(1); j++)
{
if(array[i, j] == value)
{
exists = true;
break;
}
}
Related
Hello looking for solution to fill 2D array with random values from 1-8 without 3 same numbers next to each other in a column or in a row.
Random random = new Random();
for (var row = 0; row < RowCount; row++)
{
for (var column = 0; column < RowCount; column++)
{
tiles[row, column] = random.Next(1, 8);
}
}
Idea is simple: fill your matrix from right to left and from top to down. To avoid duplicates at any cell look two cells up and two cells left, and if they have same value, call random.Next(..) again. Next code will create that matrix:
// this method checks cells that up to current
private static bool EqualsUp(int i, int j, int[,] matrix, int value) => i >= 0 && matrix[i, j] == value;
// this method checks cells that left to current
private static bool EqualsLeft(int i, int j, int[,] matrix, int value) => j >= 0 && matrix[i, j] == value;
public static int[,] GenerateMatrix(int h, int w)
{
var matrix = new int[h, w];
var random = new Random();
for (var i = 0; i < h; ++i)
for (var j = 0; j < w; ++j)
while (true)
{
var cellValue = random.Next(1, 9); // note: second value is exclusive, so to generate values from 1 to 8 pass 9 as second argument
if (EqualsUp(i - 1, j, matrix, cellValue) && EqualsUp(i - 2, j, matrix, cellValue))
continue; // need to regenerate cellValue
if (EqualsLeft(i, j - 1, matrix, cellValue) && EqualsLeft(i, j - 2, matrix, cellValue))
continue; // need to regenerate cellValue
matrix[i, j] = cellValue;
break;
}
return matrix;
}
The below IndexOutOfRangeException is not letting my code run (it compiles). While I understand this kind of exception (array indexes etc) the issue is, what I am trying to do is simply update the String subsection2 with the value in cell B[excelrow]. For some reason, there is an index out of bounds exception which to me does not make sense. Neither subsection2 or excelrow is part of an array. The only array I can think of is the excel array, but excelrow is an integer with value of 3, it should updated to row B3, and so on. (I've even tried updating with B3 directly and I get the same error).
To help you out further with context, this method called createsource takes as input the excel spreadsheet and the total rows in that sheet. It does the below code to output a 2D array containing in the first dimension the excel index of each new order (each different customer), and the 2nd dimension is the number of items ordered per customer.
The method for the code is below:
private int[,] createsource(Microsoft.Office.Interop.Excel.Worksheet xlWorksheet, int totalRows)
{
String subsection = "";
object subsection2 = "";
int orders = 0;
//figures out how many different pages there are going to be
for (int n = 3; n < totalRows + 1; n++)
{
if (!(xlWorksheet.get_Range("B" + n.ToString()).Text == subsection))
{
subsection = xlWorksheet.get_Range("B" + n.ToString()).Text;
orders++;
}
}
MessageBox.Show(orders.ToString());
int[,] source = new int[orders, 2];
int excelrow = 3;
subsection2 = xlWorksheet.get_Range("B" + excelrow.ToString()).Text;
int i;
for (i = 0; i < orders + 1; i++)
{
int j = 1;
if (excelrow == totalRows + 1)
{
break;
}
//Out of bounds exception is found in the below if statement updating subsection2:
if (!(xlWorksheet.get_Range("B" + excelrow.ToString()).Text == subsection2))
{
source[i, 0] = excelrow;
//MessageBox.Show(xlWorksheet.get_Range("B" + excelrow.ToString()).Text.ToString());
subsection2 = xlWorksheet.get_Range("B" + excelrow.ToString()).Text;
excelrow++;
}
for (int iter = 0; iter < 1;)
{
if (excelrow == totalRows + 1)
{
break;
}
if (xlWorksheet.get_Range("B" + excelrow.ToString()).Text == subsection2)
{
excelrow++;
j++;
}
if (!(xlWorksheet.get_Range("C" + excelrow.ToString()).Text == subsection2))
{
subsection2 = xlWorksheet.get_Range("C" + excelrow.ToString()).Text;
iter = 1;
}
}
source[i, 1] = j;
}
MessageBox.Show(source[2, 0].ToString());
return source;
}
I see the problem. You're declaring source as:
int[,] source = new int[orders, 2];
... okay, but look at your loop:
for (i = 0; i < orders + 1; i++)
... which later feeds into:
source[i, 0] = excelrow;
Okay, so if orders = 100, you've declared a 100 long array, going from 0-99. Then your loop, you go from 0 to "less than 100+1", aka 0-100. When you get to the last loop, you're using a value of i=100, and trying to put it into the array spot that doesn't exist.
You need to either decrease your loop by one, or increase your array size by 1.
I am wanting to create a 2d array to produce a grid of int values the size of the grid needs to be 100 * 100
Example Grid
1 2 3 .........100
101 102 103.........200
201 202 303.........300
I produced ths
int rows = 100;
int columns = 100;
public int[,] InitIntArray() {
int[,] grid = new int[rows,columns];
int number = 1;
for (int i = 0; i != rows; i++)
{
for (int j = 0; j != columns; j++)
grid[i, j] = number;
number++;
}
return grid;
}
When I use my code everything seems to work fine until I try to access the columns. all I get when I use grid.getValue() is 1.
Missed one curvy
for (int i = 0; i != rows; i++)
{
for (int j = 0; j != columns; j++)
{
grid[i, j] = number;
number++;
}
}
for (int i = 0; i < rows; i++)
And the other for-loop
for (int j = 0; j < columns; j++)
{
grid[i, j] = number;
number ++;
}
You might want to read on how for-loops work, http://www.thegeekstuff.com/2012/12/c-loops-examples/
I want to manually sort a 2D Array in C#.
I am confused on what to do when the pointer is on index 0 and I need to go to the previous row.
My problem when I reach to index 0 I cant go any further and it is then out of bounds.
int temp3 = 25;
bool swap = false;
bool swap2 = false;
long pointer = productarray[4,4];
for(int i = 4; i >= 0; i--){
for(int j = 4; j >= 0; j--){
int temp5 = 1;
while(swap != true){
if(temp3 != temp5){
pointer = productarray[i,j];
if (pointer < productarray [i, j - temp5]) {
long temporary = productarray [i, j];
productarray [i, j] = productarray [i, j - temp5];
productarray [i, j - temp5] = temporary;
temp5 = 1;
} else {
temp5++;
}
}
else{
swap = true; //Current pointer is the greatest int
temp3--;
}
}
swap = false;
}
}
Something like this
var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
from How can I sort a 2d array using Linq?
I have a 2-dimensional array with user-entered values. I need to find sum of the even elements in the diagonal of the array.
I know how to declare the array and get it filled by the user, but I'm not sure what even elements in the main diagonal really means.
I know I can find out if a number is even by saying:
if n / 2 == 0
Once I've reported the sum of the even elements in the diagonal, I would like to replace all 0 values in the array with ones.
Diagonal means all places where x and y cordinates are the same
Do if your array contains:
1 3 8 5
3 3 9 7
4 4 5 7
5 1 7 4
Then the diagonal are in bold.
Assuming the array is a square:
int sum = 0;
for(int i = 0; i < numOfArrayRows; i++)
{
//Use the mod operator to find if the value is even.
if(array[i][i] % 2 == 0)
sum += array[i][i];
//Change 0's to ones
for(int j = 0; j < numOfArrayCols; j++)
if(array[i][j] == 0)
array[i][j] = 1;
}
Also, next time add the "Homework" tag if you have a homework question :P
With a two-dimensional array it's really easy, since you don't need any index magic:
int a[N][N] = ...;
int sum = 0;
for(int i=0; i<N; ++i)
if(a[i][i] % 2 == 0) //or a[i] & 1, if you like, just check if it's dividable by 2
sum += a[i][i];
This C++ code shouldn't be that different in C or C#, but you should get the point. Likewise the second question would be as simple as:
int a[M][N] = ...;
for(i=0; i<M; ++i)
for(j=0; j<N; ++j)
if(a[i][j] == 0)
a[i][j] = 1;
And I suspec that the main diagonal is the one that begins with coordinates 0,0.
To replace 0 elements with 1 you would do something like:
if (array[i,j] == 0) array[i,j] == 1;
This sounds like homework - however I will help out :)
So if you have an 2D array, and in order to find the sum of the diagonal values, you will know that the indices of both of the values would match in order to provide you with each of the diagonal values.
To iterate through these you could use a simple loop that would sum up every diagonal value, as shown:
//Your Sum
int sum = 0;
//This will iterate and grab all of the diagonals
//You don't need to iterate through every element as you only need
//the diagonals.
for(int i = 0; i < sizeOfArray; i++)
{
//This will add the value of the first, second, ... diagonal value to your sum
sum += array[i,i];
}
To set each of the values that is 0 to 1, you could iterate through each element of the array and check if the value is 0, then set that value to 1, for example:
for(int i = 0; i < sizeOfArray; i++)
{
for(int j = 0; j < sizeOfArray; j++)
{
//Check if this value is 0;
//If it is 0, set it to 1, otherwise continue
}
}
int[,] array = new int[,] {{1,2,3},
{4,5,6},
{7,8,9}};
//Suppose you want to find 2,5,8
for(int row = 0; row < 3; row++)
{
for(int column = 0; column < 3; column++)
{
if((row == 0 && column == 1) || (row == 1 && column == 1) || (row == 2 && column == 1))
{
Console.WriteLine("Row: {0} Column: {1} Value: {2}",row + 1, column + 1, array[row, column]);
}
}
}
Here is the code you need, not much explain:
//Read the size of the array, you can get it from .Count() if you wish
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
//Reading all the values and preparing the array (a)
for (int a_i = 0; a_i < n; a_i++)
{
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp, Int32.Parse);
}
//performing the operation (google what diagonal matrix means)
int PrimarySum = 0, SecondarySum = 0;
for (int i = 0; i < n; i++)
{
//The If condition is to skip the odd numbers
if (a[i][i] % 2 == 0) { PrimarySum += a[i][i]; }
//For the reverse order
int lastelement = a[i].Count() - 1 - i;
if (a[i][lastelement] % 2 == 0) { SecondarySum += a[i][lastelement]; }
}
//Get the absolute value
Console.WriteLine(Math.Abs(PrimarySum - SecondarySum).ToString());
Console.ReadKey();