how to initialize ArrayObject value to ZERO in C# - c#

I have
Cell[,] cells = new Cells[6,6];
I want to initialize it all values to zero
I did something like this
for(int i=1; i<=6;i++) {
for(int j=1; j<=6; j++) {
cells[i,j] = 0;
}
}
The problem is it cant convert int 0 to Cell type. How do I initializze them to zero for first time?? For eg: I have [6,6] array and I want to assign every Cell[2,3].Value = 0
Thanks

The problem is it cant convert int 0 to Cell type. How do I initializze them to zero for first time??
Going by your Class make x and y public first (assuming you are accessing them in methods not in your Cell class:
class Cell
{
public int x;
public int y;
Warrior warrior;
};
Then you should get access to your class members:
Cell[,] cells = new Cells[6,6];
for(int i=0; i<6;i++)
{
for(int j=0; j<6; j++)
{
cells[i,j].x = cells[i,j].y = 0;
}
}
The above is for resetting the values to 0. If you want this on initialization then create a constructor:
Cell(Warrior getWarrior)
{
x = 0;
y = 0;
warrior = getWarrior;
}
Cells[,] cells = new Cells[6, 6];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
cells[i, j]= new Cells(sendWarrior);
Console.WriteLine("\t{0} {1}", cells[i, j].x, cells[i, j].y);
}
}

You can put it like that:
class Cell {
public int x {get; set;}
public int y {get; set;}
Warrior warrior {get; set;}
};
Cell[,] cells = new Cells[6, 6];
// Arrays are zero-based in C#, so they start with 0
for(int i = 0; i < Cells.GetLength(0); i++) // <- Better get length than put "6"
for(int j = 0; j < Cells.GetLength(1); j++)
cells[i, j] = new Cell() { // <- Do not forget to create Cell
x = 0, // <- Overshoot, x will be 0 by default, to show the trick only
y = 0 // <- Overshoot, y will be 0 by default, to show the trick only
};

Related

Initialize array of a class with fixed length and dynamically add values in C#

I want to have a two-dimensional game board, and every field is a custom class with information about this field, with properties. The size of the game board is known on instantiation, the values of the properties are not. After instantiation, I want to randomly set them for each field. My initial idea was to create an array, not a list, because the size of the game board is always fixed.
public class GameBoard
{
private int _xValue;
private int _yValue;
private int _bombs;
private int _fields;
public Field[][] gameBoard;
public GameBoard(int x, int y)
{
_xValue = x;
_yValue = y;
_fields = _xValue * _yValue;
gameBoard = new[] { new Field[_xValue], new Field[_yValue] };
//Here I have to initialize every Field
for (int i = 0; i < _xValue; i++)
{
for (int j = 0; j < _yValue; j++)
{
//Set properties of Field
//For example: gameBoard[i][j].IsBomb = RandomBoolean;
//Here I get NullReferenceExceptions
}
}
}
}
I do understand why this does not work. I tried lists, two-dimensional arrays or, like at the moment, a jagged array, what I would prefer. How can I solve this problem in a readable, clean way?
EDIT
The Field class:
public class Field
{
public bool IsBomb { get; set; }
public bool IsFlagged { get; set; }
}
I tried to add gameBoard[i][j] = new Field(); inside the nested forloop. This leads to an IndexOutOfRangeException.
Here is your array-property:
public Field[,] gameBoard;
And here is initialization:
public GameBoard(int x, int y)
{
_xValue = x;
_yValue = y;
_fields = _xValue * _yValue;
gameBoard = new Field[_xValue, _yValue];
for (int i = 0; i < _xValue; i++)
{
for (int j = 0; j < _yValue; j++)
{
gameBoard[i, j] = new Field();
}
}
}
Lots of confusion in here on how to work with jagged arrays. If you want to work with jagged arrays, you have to setup in such a way
//Declare jagged array, I want _xValue arrays
Field[][] gameBoard = new Field[_xValue][];
for (int i = 0; i < _xValue; i++)
{
gameBoard[i] = new Field[_yValue];
for (int j = 0; j < _yValue; j++)
{
gameBoard[i][j] = new Field(){ IsBomb = RandomBoolean};
}
}
The equivalent in a multi-dimensional array would be
//Declare multi-dimensional array of size _xValue x _yValue
Field[,] gameBoard2 = new Field[_xValue, _yValue];
for(int i = 0; i < _xValue; i++)
{
for(int j = 0; j < _yValue; j++)
{
// Instantiate the Field object at x,y
gameBoard2[i, j] = new Field { IsBomb = RandomBoolean };
}
}

Convert object containing 2D object array into string array

I have a method which returns the following type and object:
object {object[,]}
test {object[19, 2]}
Is it possible to convert this into 2d string array, or a datatable?
Looks akward, but I haven't found another way.
int firstDimensionSize = 19;
int secondDimensionSize = 2;
object[,] objectArray = new object[firstDimensionSize, secondDimensionSize];
string[,] stringArray = new string[objectArray.Length / secondDimensionSize, secondDimensionSize];
for (int i = 0; i < objectArray.Length / secondDimensionSize; i++)
{
for (int j = 0; j < secondDimensionSize; j++)
{
stringArray[i, j] = objectArray[i, j].ToString();
}
}
In case your second dimension is always the same you could leave out the inner loop, replacing it with static code.
See also https://www.dotnetperls.com/2d
I made this extension method, but you can aswell make it a normal method if you don't need it that often.
public static class Extensions
{
public static string[,] ConvertToString2D(this object[,] arr)
{
int dim1 = arr.GetLength(0);
int dim2 = arr.GetLength(1);
string[,] strArray = new string[dim1, dim2];
for (int i = 0; i < dim1; i++)
{
for (int j = 0; j < dim2; j++)
{
strArray[i, j] = Convert.ToString(arr[i, j]);
}
}
return strArray;
}
}
and then you can call it like this:
var result = objArr.ConvertToString2D();

Show sublist value from index C#

My problem is I have M subproblem. Each subproblem include x (double array) and reduced cost which has different value for each iteration m. I want to show x which has the minimum reduced cost among all subproblems. here is my class:
public class Subproblem
{
public double[,] x { get; set; }
public double ReducedCost { get; set; }
}
So far, I already can get the minimum Reduced Cost and index of it. Now I want to show x value (double array) which on that index. I've code like this:
var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];
s.ReducedCost = model.ObjVal;
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
s.x[i, j] = x[i, j].X;
}
}
sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));
the last line (Console.WriteLine(sub.x(minRCIndex));) still got red underline, I don't know how to write it
If you are only trying to get the minimum Reduced Costed subproblem you should be doing:
Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];
And you can print the matrix down like this:
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
}
Console.Write("\n");
}
But you seem a little confused. You are pushing a Subproblem into your sub list with the same object for M times. Because model.ObjVal doesn't change along the first for loop. There is something wierd going on there too.
It should be
var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.WriteLine(objWithMinReduceCost.x[i, j]);
}
}
If you are interested in obtaining the double array, you could just do this:
double[,] result = sub.First(i => i.ReducedCost == minRC).x;
Although as Tolga mentioned, all your elements will have the same ReducedCost with your current code.

What is the most efficient way to find the largest element in a matrix along with position? Also, the largest element in each column with position

I have written the following code but it looks to be far from efficient.
//Find largest in tempRankingData
int largestIntempRankingData = tempRankingData[0, 0];
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] > largestIntempRankingData)
{
largestIntempRankingData = tempRankingData[i, j];
}
}
}
//Find position of largest in tempRankingData
List<string> positionLargestIntempRankingData = new List<string>();
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] == largestIntempRankingData)
{
positionLargestIntempRankingData.Add(i + "," + j);
}
}
}
//Find largest in each column
int largestInColumn = 0;
List<string> positionOfLargestInColumn = new List<string>();
Dictionary<int, List<string>> position = new Dictionary<int, List<string>>();
for (int i = 0; i < count; i++)
{
largestInColumn = tempRankingData[0, i];
positionOfLargestInColumn = new List<string>();
for (int j = 0; j < count; j++)
{
if (tempRankingData[j, i] > largestInColumn)
{
largestInColumn = tempRankingData[j, i];
}
}
for (int j = 0; j < count; j++)
{
if (tempRankingData[j, i] == largestInColumn)
{
positionOfLargestInColumn.Add(j + "," + i);
}
}
position.Add(i, positionOfLargestInColumn);
}
So, I wanted to check about the most efficient way to do this.
Whilst you're finding the largest in each column, you could also be finding the largest overall. You can also capture the positions as you go:
//Find largest in each column
int largestInColumn = 0;
int largestOverall = int.MinValue;
List<string> positionOfLargestInColumn;
Dictionary<int, List<string>> position = new Dictionary<int, List<string>>();
List<string> positionLargestIntempRankingData = new List<string>();
for (int i = 0; i < count; i++)
{
largestInColumn = tempRankingData[0, i];
positionOfLargestInColumn = new List<string>();
positionOfLargestInColumn.Add("0," + i);
for (int j = 1; j < count; j++)
{
if (tempRankingData[j, i] > largestInColumn)
{
largestInColumn = tempRankingData[j, i];
positionOfLargestInColumn.Clear();
positionOfLargestInColumn.Add(j + "," + i);
}
else if(tempTankingData[j,i] == largestInColumn)
{
positionOfLargestInColumn.Add(j + "," + i);
}
}
position.Add(i, positionOfLargestInColumn);
if(largestInColumn > largestOverall)
{
positionLargestIntempRankingData.Clear();
positionLargestIntempRankingData.AddRange(positionOfLargestInColumn);
largestOverall = largestInColumn;
}
else if(largestInColumn == largestOverall)
{
positionLargestIntempRankingData.AddRange(positionOfLargestInColumn);
}
}
1). You can find largest element and its position in one method and retrieve.
Would be caller of your method concerned about position or actual value, is a matter of concrete case.
2) You can use `yield return' technique in your matrix search (for column based search), so do not compute all column's maximas and push them into the dictionary. Dictionaries are not that fast as arrays, if you can avoid use them, do that.
3) You can keep a matrix in single dimension, long array. Have [] access operator overload, to "emulate" matrix access. Why ? If finding maximum is something frequent you might need to do during program run, having one foreach loop is faster then having 2 nested once. In case of a big matrices, single array search can be easily parallelized among different cores.
If big matrices and/or frequent calls are not your concern, just simplify your code like in points (1), (2).
For your fist two itterations you could replace with this:
//Find largest in tempRankingData
int largestIntempRankingData = tempRankingData[0, 0];
List<KeyValuePair<double,string>> list = new List<KeyValuePair<double,string>>();
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] > largestIntempRankingData)
{
largestIntempRankingData = tempRankingData[i, j];
list.Add(new KeyValuePair<double, string>(largestIntempRankingData, i + "," + j)); //Add the value and the position;
}
}
}
//This gives a list of strings in which hold the position of largestInItemRankingData example "3,3"
//Only positions where the key is equal to the largestIntempRankingData;
list.Where(w => w.Key == largestIntempRankingData).ToList().Select(s => s.Value).ToList();
You can get all these pieces of information in a single scan with a little fiddling around. Something like this (converting the rows and columns to a string is trivial and better done at the end anyway):
int? largestSoFar = null; // you could populate this with myMatrix[0,0]
// but it would fail if the matrix is empty
int largestCol = 0;
int largestRow = 0;
int?[] largestPerColumn = new int?[numOfCols]; // You could also populate this with
// the values from the first row but
// it would fail if there are no rows
int[] largestColumnRow = new int[numOfCols];
for (int i = 0; i < numOfRows; i++)
{
for (int j = 0; j < numOfCols; i++)
{
if (largestSoFar < myMatrix[i,j])
{
largestSoFar = myMatrix[i,j];
largestCol = j;
largestRow = i;
}
if (largestPerColumn[j] < myMatrix[i,j])
{
largestPerColumn[j] = myMatix[i,j];
largestColumnRow[j] = i;
}
}
}
// largestSoFar is the biggest value in the whole matrix
// largestCol and largestRow is the column and row of the largest value in the matrix
// largestPerColumn[j] is the largest value in the jth column
// largestColumnRow[j] is the row of the largest value of the jth column
If you do need to capture all the "maxima" (for want of a better word, because that's not really what you are doing) in a column, you could just change the above code to something like this:
int? largestSoFar = null; // you could populate this with myMatrix[0,0]
// but it would fail if the matrix is empty
int largestCol = 0;
int largestRow = 0;
int?[] largestPerColumn = new int?[numOfCols]; // You could also populate this with
// the values from the first row but
// it would fail if there are no rows
List<int>[] largestColumnRow = new List<int>[numOfCols];
for (int i = 0; i < numOfRows; i++)
{
for (int j = 0; j < numOfCols; i++)
{
if (largestSoFar < myMatrix[i,j])
{
largestSoFar = myMatrix[i,j];
largestCol = j;
largestRow = i;
}
if (largestPerColumn[j] < myMatrix[i,j])
{
largestPerColumn[j] = myMatix[i,j];
largestColumnRow[j].Add(i);
}
}
}
// Now largestColumnRow[j] gives you a list of all the places where you found a larger
// value for the jth column

2 dimensional array

For each element in the array I need a unique identifier such as Seat1, Seat2, Seat 3....... all the way to the end of the length of the array.
currently I have done the following:
int rows = 10, cols = 10;
bool[ , ] seatArray = new bool[rows , cols]; //10 rows, 10 collums
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++ )
{
seatArray[i, j] = false;
}
foreach (bool element in seatArray)
{
Console.WriteLine("element {0}", element);
}
}
this simply just says "Element False" x 100 in the console.
i need to replace "Element" with Seat1, Seat2, Seat3....to the end of the array length.
any help will be much appreciated!
thank you!
Create a Seat class (or structure, if more appropriate) with ID and Occupied(?) properties. Make an array of this type.
public class Seat
{
public string ID { get; set; }
public bool Occupied { get; set; }
}
int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];
for (int i = 0; i < rows; ++i )
{
for (int j = 0; j < cols; ++j)
{
seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
}
}
foreach (var seat in seats)
{
Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
int count = 1;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++ )
{
seatArray[i, j] = count;
count++;
}
foreach (bool element in seatArray)
{
Console.WriteLine("element {0}", element);
}
no idea what language this is so idk the syntax but just do some external counter to number them
that just says false every time you set every one to false, dont use a bool, or write a class to hold the true false and number info
tvanfosson, i am struggling to make your coding work, iv put it into a new class off my main method see below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Class1
{
public class Seat
{
public string ID { get; set; }
public bool Occupied { get; set; }
}
int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];
for (int i = 0; i < rows; ++i )
{
for (int j = 0; j < cols; ++j)
{
seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
}
}
foreach (var seat in seats)
{
Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
}
}
is this correct as i seem to be receiving a lot of syntax errors
thank you!

Categories

Resources