Creating a big array C# - c#

I'm very, very new to C# and would like to ask a maybe very stupid question, the first language I learned was Java, in which I could do this:
int[][] array = new int[1600][900];
array[600][400] = 10;
for(int x = 0; x < 1600; x++)
{
for(int y = 0; y < 900; y++)
{
int something = colour[x][y];
}
}
Now I've searched the web for quite a while, but I've got no idea about how to do this in C#
EDIT:
Thanks for the help everyone, it's been usefull :)

Just use a comma :
int[,] array = new int[1600,900];
array[600,400] = 10;
//...

You can do it in a very similar way in C#:
int[,] array = new int[1600,900];
array[600,400] = 10;
for(int x = 0; x < 1600; x++)
{
for(int y = 0; y < 900; y++)
{
int something = colour[x,y];
}
}
I'm not sure if I understand what's the purpose of the code in the double for cycle. I suppose those three pieces of code don't have anything in common.

int [,] array = new int[1600,900];

To add some color to the answers:
In .NET, an int[][] is a jagged array, or an array of arrays. While this may be a perfectly good structure for you to use, it has the addded overhead that each array must be initialized individually. So your initialization would be:
int[][] array = new int[1600][];
for(int i=0;i<array.Length;i++)
array[i] = new int[900];
now you can access an individual value by using
array[600][400] = 10;
One benefit of using jagged arrays is that the "interior" array can be different sizes. If you don;t need that flexibility than using a rectangular ([,]) array may be a better option for you.

Related

C# Matrix of arrays

I'm writing a program in c# that associates an array of 12 elements to a triplet of values. I would like to store my data in a matrix of dimension [n,m,p], but where each element is actually an array. The real world application is saving the output of 12 sensors for each point in a 3D cartesian space.
I tried something like this:
int[][,,] foo = new int[12][,,];
But this, if I'm right, creates an array of 12 matrices 3x3, while i want a NxMxP matrix of 12 elements arrays.
If I try to specify the matrix dimensions like this:
int[][,,] foo = new int[12][N,M,P];
I get error CS0178 (Invalid rank specifier: expected ',' or ']') and CS1586 (Array creation must have array size or array initializer).
I'm still learning c#, please excuse me for the trivial question, but I can't wrap my head around this. I'm using visual studio 2015.
If you want to create 12 instances of [N, M, P] matrices organized as an array (please, notice that int[][,,] is array of matrices, not matrix of arrays):
int[][,,] foo = Enumerable
.Range(0, 12)
.Select(_ => new int[N, M, P])
.ToArray();
Or
int[][,,] foo = Enumerable
.Repeat(new int[N, M, P], 12)
.ToArray();
If you prefer loop
// please, notice the different declaration:
int[][,,] foo = new int[12];
for (int i = 0; i < foo.Length; ++i)
foo[i] = new int[N, M, P];
Edit: if you want [N, M, P] matrix of arrays (see comments):
I'm trying to get NMP instances of 12-elements arrays, addressable by
the n,m,p indices
// please, notice the different declaration: matrix of arrays
int[,,][] foo = new int[N, M, P][];
for (int i = 0; i < foo.GetLength(0); ++i)
for (int j = 0; j < foo.GetLength(1); ++j)
for (int k = 0; k < foo.GetLength(2); ++k)
foo[i, j, k] = new int[12];
Try using a 4 dimensional array.
int[,,,] foo = new int[N,M,P, 12];
int[][,,] foo
You are creating an array of 3-D arrays (of int). If you want to initialize that array then you would have to do this:
int[][,,] foo = new int[12][,,];
And then loop through foo and for each cell initialize the 3-D array:
foo[i] = new int[M,N,P];
You can use some LINQ to make it a one-liner (see Dmitry's answer), but it basically amounts to the same thing.
Multi-dimensional arrays in C# are kind of a pain to work with.
I don't know if it will help you (maybe you need only arrays) but you can try to create simple Point3D class. This will improve readibility and, I think, maintanance.
public class Point3D
{
int X { get; set; }
int Y { get; set; }
int Z { get; set; }
public Point3D(int x, int y, int z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
}
And then:
Point3D[] arrayOfPoints = new Point3D[12];
arrayOfPoints[0] = new Point3D(0, 2, 4);

Finding the next available position in an array

I have a two-dimensions array of a fixed size of 50 elements. I need to ask the user for some values and insert them into the array. The problem is "How do I make sure I'm not overwriting anything that's in there?"
There will already be some content in the array when I start the program, but I don't know how much. How can I find the next available ID in the array, to insert my content there without overwriting anything that could be already in there?
I tried using array.GetUpperBound and array.GetLength, however they return fixed values no matter how many elements are already in the array.
I have to use an array, I can't use lists or anything like that.
What can I do to find out the next "free" position in my array?
Thank you very much for helping.
Well if you are using Array, all your values will contain a default value.For example if you have an two-dimensional int array like this:
var arr = new int[2, 3];
arr[1,2] will be equal to 0 which is default value for int.Anyway you can define an extension method to find available position for a two-dimensional array like this:
public static class MyExtensions
{
public static void FindAvailablePosition<T>(this T[,] source, out int x, out int y)
{
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j].Equals(default(T)))
{
x = i;
y = j;
return;
}
}
}
x = -1;
y = -1;
}
}
And you can use it like this:
var arr = new int[2, 3];
arr[0, 0] = 12; // for example
int x, y;
arr.FindAvailablePosition(out x,out y);
// now x = 0, y = 1

How to keep the latest X elements of a list

I need to use a data structure that would keep the latest X elements of a list. A colleague gave me this solution:
int start = 0;
const int latestElementsToKeep = 20;
int[] numbers = new int[latestElementsToKeep];
for (int i = 0; i < 30; i++)
{
numbers[start] = i;
if (start < numbers.Length - 1)
{
start++;
}
else
{
start = 0;
}
}
So after this is run, the numbers array has numbers 19-29 (the latest 20 numbers).
That's nice, but difficult to use this in the real world. Is there an easier way to do this?
This seems like a pretty standard Circular Buffer. My only suggestion would be to create a class for it or download one of the libraries available. There seem to be a few promising looking ones near the top of the Google results.
Easier way to do this:
int[] numbers = new int[latestElementsToKeep];
for (int i = 0; i < 30; i++)
numbers[i % latestElementsToKeep] = i;
Modulus operator returns the reminder of dividing i by latestElementsToKeep. When i reaches latestElementsToKeep, you will start from the beginning.
For a range of numbers, you can use:
int keep = 20;
int lastItem = 29;
int[] numbers = Enumerable.Range(lastItem - keep, keep).ToArray();
To get the last items from any collection (where you can get the size), you can use:
int keep = 20;
someType[] items = someCollection.Skip(someCollection.Count() - keep).ToArray();

How to create array of 100 new objects?

I'm trying something like that:
class point
{
public int x;
public int y;
}
point[] array = new point[100];
array[0].x = 5;
and here's the error:
Object reference not set to an instance of an object. (# the last line)
whats wrong? :P
It only creates the array, but all elements are initialized with null.
You need a loop or something similar to create instances of your class.
(foreach loops dont work in this case)
Example:
point[] array = new point[100];
for(int i = 0; i < 100; ++i)
{
array[i] = new point();
}
array[0].x = 5;
When you do
point[] array = new point[100];
you create an array, not 100 objects. Elements of the array are null. At that point you have to create each element:
array[0] = new point();
array[0].x = 5;
You can change class point to struct point in that case new point[500] will create an array of points initialized to 0,0 (rather than array of null's).
As the other answers explain, you need to initialize the objects at each array location. You can use a method such as the following to create pre-initialized arrays
T[] CreateInitializedArray<T>(int size) where T : new()
{
var arr = new T[size];
for (int i = 0; i < size; i++)
arr[i] = new T();
return arr;
}
If your class doesn't have a parameterless constructor you could use something like:
T[] CreateInitializedArray<T>(int size, Func<T> factory)
{
var arr = new T[size];
for (int i = 0; i < size; i++)
arr[i] = factory();
return arr;
}
LINQ versions for both methods are trivial, but slightly less efficient I believe
int[] asd = new int[99];
for (int i = 0; i < 100; i++)
asd[i] = i;
Something like that?
Sometimes LINQ comes in handy. It may provide some extra readability and reduce boilerplate and repetition. The downside is that extra allocations are required: enumerators are created and ToArray does not know the array size beforehand, so it might need to reallocate the internal buffer several times. Use only in code whose maintainability is much more critical than its performance.
using System.Linq;
const int pointsCount = 100;
point[] array = Enumerable.Range(0, pointsCount)
.Select(_ => new point())
.ToArray()

Redim Preserve in C#?

I was shocked to find out today that C# does not support dynamic sized arrays. How then does a VB.NET developer used to using ReDim Preserve deal with this in C#?
At the beginning of the function I am not sure of the upper bound of the array. This depends on the rows returned from the database.
VB.NET doesn't have the idea of dynamically sized arrays, either - the CLR doesn't support it.
The equivalent of "Redim Preserve" is Array.Resize<T> - but you must be aware that if there are other references to the original array, they won't be changed at all. For example:
using System;
class Foo
{
static void Main()
{
string[] x = new string[10];
string[] y = x;
Array.Resize(ref x, 20);
Console.WriteLine(x.Length); // Prints out 20
Console.WriteLine(y.Length); // Still prints out 10
}
}
Proof that this is the equivalent of Redim Preserve:
Imports System
Class Foo
Shared Sub Main()
Dim x(9) as String
Dim y as String() = x
Redim Preserve x(19)
Console.WriteLine(x.Length)
Console.WriteLine(y.Length)
End Sub
End Class
The two programs are equivalent.
If you truly want a dynamically sized collection, you should use List<T> (or something similar). There are various issues with using arrays directly - see Eric Lippert's blog post for details. That's not to say you should always avoid them, by any means - but you need to know what you're dealing with.
Use ArrayLists or Generics instead
Use a List<T>. It will dynamically size as needed.
You really shouldn't be using ReDim, it can be very expensive. I prefer List(Of T), but there are many options in this area.
That said, you had a question and here is your answer.
x = (int[]) Utils.CopyArray((Array) x, new int[10]);
I couldn't help but notice that none of the above answers approach the concept of multidimensional arrays. That being said, here's an example. The array in question is predefined as x.
int[,] temp = new int[newRows, newCols];
int minRows = Math.Min(newRows, x.GetUpperBound(0) + 1);
int minCols = Math.Min(newCols, x.GetUpperBound(1) + 1);
for (int i = 0; i < minRows ; ++i)
for (int j = 0; j < minCols; ++j)
temp[i, j] = x[i, j];
x = temp;
Just for fun, here's one way to use generics in order to redim/extend a unidimensional array (add one more "row") :
static T[] Redim<T>(T[] arr, bool preserved)
{
int arrLength = arr.Length;
T[] arrRedimed = new T[arrLength + 1];
if (preserved)
{
for (int i = 0; i < arrLength; i++)
{
arrRedimed[i] = arr[i];
}
}
return arrRedimed;
}
And one to add n rows (though this doesn't prevent user from undersizing the array, which will throw an error in the for loop) :
static T[] Redim<T>(T[] arr, bool preserved, int nbRows)
{
T[] arrRedimed = new T[nbRows];
if (preserved)
{
for (int i = 0; i < arr.Length; i++)
{
arrRedimed[i] = arr[i];
}
}
return arrRedimed;
}
I'm sure you get the idea.
For a multidimensional array (two dimensions), here's one possibility:
static T[,] Redim<T>(T[,] arr, bool preserved)
{
int Ubound0 = arr.GetUpperBound(0);
int Ubound1 = arr.GetUpperBound(1);
T[,] arrRedimed = new T[Ubound0 + 1, Ubound1];
if (preserved)
{
for (int j = 0; j < Ubound1; j++)
{
for (int i = 0; i < Ubound0; i++)
{
arrRedimed[i, j] = arr[i, j];
}
}
}
return arrRedimed;
}
In your program, use this with or even without the type specified, the compiler will recognize it :
int[] myArr = new int[10];
myArr = Redim<int>(myArr, true);
or
int[] myArr = new int[10];
myArr = Redim(myArr, true);
Not sure if all this is really relevant though. =D
Please feel free to correct me or improve my code. ;)
Even though it's a long time ago it might help someone looking for a simple solution - I found something great in another forum:
//from Applied Microsoft.NET framework Programming - Jeffrey Richter
public static Array RedimPreserve(Array origArray, Int32 desiredSize)
{
System.Type t = origArray.GetType().GetElementType();
Array newArray = Array.CreateInstance(t, desiredSize);
Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize));
return newArray;
}
Source: https://social.msdn.microsoft.com/Forums/en-US/6759816b-d525-4752-a3c8-9eb5f4a5b194/redim-in-c?forum=csharplanguage

Categories