How to assign value in two dimensional array - c#

How to assign value in two dimensional array in c#
My Code is
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 5; y++)
{
matarix[x, y] = x+"-"+y;
}
}
i tried above code but its showing error "can't implicitly convert string to int"
How to do it ? Thanks

You're on the right track. Just assign a value.
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 5; y++) {
matarix[x, y] = VALUE_HERE;
}
}
One recommendation I would make, would be to use Array.GetLength instead of hard coding your for loops. Your code would become:
int[,] matarix = new int[4, 5];
for (int x = 0; x < matarix.GetLength(0); x++) {
for (int y = 0; y < matarix.GetLength(1); y++) {
matarix[x, y] = VALUE_HERE;
}
}
You pass in one of the array's dimensions, and it tells you how many indices exist for that dimension.

This is a template I usually use for filling up two dimensional arrays.
Its one line and easy to change.
int[,] Foo = new int[4,5];
for(int i=0;i < Foo.Length; i++, Foo[i % Foo.GetLength(0),i / Foo.GetLength(1)] = 0; // Or value to assign
Also please do note that your array is holding integers while you are giving it strings (the "" converts it to a string, while x - y keeps it integer)
Hope it helps

Related

How to eliminate duplicates in 2D arrays in C#

just started to learn programming and I need 2D array without duplicates. This code (well edited for 1D) worked just fine for 1D but doesn't for 2D and have no clue why.
Would be very happy if someone helped me. Thanks.
Random r = new Random();
int[,] array = new int[10, 8];
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = r.Next(10, 100);
for (int k = 0; k < i; k++)
{
for (int l = 0; l < j; l++)
{
if (array[i,j] == array[k,l])
{
i--;
j--;
break;
}
}
}
}
}
With the nested j loop you are filling the entire second dimension for each i, but in the k and l loops you are only checking the grid to the upper and left of current cell. You could place a number twice because you are not checking every previously filled location.
If we change the code to this:
for (int k = 0; k < array.GetLength(0); k++)
{
for (int l = 0; l < array.GetLength(1); l++)
{
if (i != k && j != l && array[i, j] == array[k, l])
{
i--;
j--;
break;
}
}
}
Then you eliminate that problem, but you very quickly find that you get a IndexOutOfRangeException because you're decrementing both i & j at the same time. That's not moving you to the previous value - it's jumping back a whole row and left one cell - and that's ultimately sending i or j to -1 and that's not good.
If you want to do it like you're attempting then you need to have a way to simply move back to the previously filled cell, regardless of the row or column you're on.
Try this:
for (int x = 0; x < array.GetLength(0) * array.GetLength(1); x++)
{
array[x % array.GetLength(0), x / array.GetLength(0)] = r.Next(10, 100);
for (int y = 0; y < x; y++)
{
if (array[x % array.GetLength(0), x / array.GetLength(0)] == array[y % array.GetLength(0), y / array.GetLength(0)])
{
x--;
break;
};
}
}
However, that's not very efficient. Try this instead:
var values = Enumerable.Range(10, 90).OrderBy(_ => r.Next()).ToArray();
for (int x = 0; x < array.GetLength(0) * array.GetLength(1); x++)
{
array[x % array.GetLength(0), x / array.GetLength(0)] = values[x];
}
So, first of all, that just seems inefficient. Not sure why you want to do it this way, but then again, don't know the reason. Looks like a programming assignment.
My guess, you need a sort of double break going on. When you break finding a match, you don't break out to the "k" for loop, so you continue looking for a match even though you found one. Try setting a boolean value to say it's found, then use that in the criteria for the for loop for k. That'll break it out and let you start over on the outside loops for i and j.
Even then, it won't work because you indescriminately subtracted i and j. So if you're on position 1,2 you will jump back to 0,1 rather than 1,2. So you need to subtract j, if it drops below 0, then subtract from i and add "array.GetLength(1)" to j.
This solution depends on HashSet's property of containing unique elements. It has an Add method that returns false when we try to add existing elements.
Random r = new Random();
int[,] array = new int[10, 8];
var usedValues = new HashSet<int>();
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
int uniqueValue;
while (true)
{
uniqueValue = r.Next(10, 100);
if (usedValues.Add(uniqueValue)) break; // It is unique indeed
// It is not unique, try again.
}
array[i, j] = uniqueValue;
}
}
The above solution is more suitable when the range of the acceptable unique values is large. In this specific case the range is very small (10-99), and the solution offered by #Enigmativity is preferable.

2D array printing C#

I want to print a 2D array, I tried using the following code, but it's only printing the first row of the array, why is it doing that and not printing the whole array in one line?
for (int x = 0, y = 0; y < 3; y++)
{
for (; x < 3; x++)
Console.Write("{0}, ", arr[x, y]);
}
Try this:
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
Console.Write("{0}, ", arr[x, y]);
}
}
Column based printing.
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
Console.Write("{0}, ", arr[x, y]);
Console.Write("\n"); //added for better formatting
}
or
If you don't care about formatting,
foreach(var arrEle in arr)
Console.Write(arrEle+" ");
The problem , with your code is that you aren't initializing x for every y. That is the reason, we have to declare/initialize in inner for-loop.
x is only set to 0 once at the start of the outer loop, so in the second two iterations of the outer loop, x=3 and the inner loop test fails. Try this:
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
Console.Write("{0}, ", arr[x, y]);
}
Just use a simple foreach loop:
foreach (var item in arr)
Console.Write("{0}, ", item);
foreach loop will do with multidimensional arrays as well.
You have defined x=0 in the outer loop. This means once the inner loop has ran once x will always be 3
Try:
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
Console.Write("{0}, ", arr[x, y]);
}

C# .NET adding items dynamically to 2-D arrays?

What is the most efficient to add items to a multi-dimensional array where you don't know the item count at the start?
You can use Array.GetLength method to get lenght of each dimension, then you can just populate your array using a simple for loop.
For example:
for(int x = 0; x < array.GetLength(0); x++)
{
for(int y = 0; y < array.GetLength(1); y++)
{
array[x,y] = "bla,bla...";
}
}

Get objects at index out of List<Object>

I'm trying to make a 2D RPG game, and would like to use a List< List< Object > > to make a grid in which I store world objects of different types. Only problem is, that I don't know how to get stuff out of this multidimensional List.
The code below creates a multidimensional List and fills it with 'Dirt' Objects (though objects[i] doesnt work, which is my problem).
public List<List<Object>> objects;
this.mapWidth = 36;
this.mapHeight = 21;
this.objects = new List<List<Object>>();
for (int y = 0; y < mapHeight; y++)
{
objects.Add(new List<Object>());
}
for (var i = 0; i < mapWidth; i++)
{
for (var j = 0; j < mapHeight; j++)
{
objects[i].Add(new Dirt());
}
}
The players has a position, e.g. 18,11, which is in the middle of this map/multidimensional List. I would like to check which 'tiles' are around him so I only have to update those things on the map. List[y][x] doesnt work.
I think your initial construction code is incorrect. Looks like you're building your grid to have mapHeight rows and mapheight columns. Rewrite the construction code to be this:
for (var y = 0; y < mapHeight; y++)
{
objects.Add(new List<Object>());
for (var x = 0; x < mapWidth; x++)
{
objects[y].Add(new Dirt());
}
}
EDIT: And I think this will produce a table where your lookup can be achieved by: Object gridEntry = objects[y][x];
EDITx2: If you like, you can rewrite the creation code to this:
for (var y = 0; y < mapHeight; y++)
{
List<Object> currentRow = new List<Object>();
objects.Add(currentRow);
for (var x = 0; x < mapWidth; x++)
{
currentRow.Add(new Dirt());
}
}

Initializing a jagged array in c# gives index out of range exception

field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < 3; y++)
{
field[x][y] = new int[3];
}
}
For some reason the above code is giving me out of range exception but the following works fine:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
}
for (int y = 0; y < input.Height; y++)
{
for (int x = 0; x < input.Width; x++)
{
field[x][y] = new int[3];
field[x][y][0] = random.Next(0, output.Width);
field[x][y][1] = random.Next(0, output.Height);
field[x][y][2] = MaskFunctions.DSCALE;
}
}
Can anyone point out what am i doing wrong?
Also: Is there a difference between out of range and out of bound exception?
Your inner loop goes from 0 to 3, instead of 0 to input.Height. This will produce an out of range exception when input.Height < 3.
You probably meant to do this:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < input.Height; y++)
{
field[x][y] = new int[3];
}
}

Categories

Resources