How to add data from 1d to 2d array in C# - c#

How can I add an array to another 2D array? For example
//change this
array2d = { {1,2,3}, {4,5,6} };
//to this
array2d = { {1,2,3}, {4,5,6}, {7,8,9} };
//by adding
array1d = {7,8,9};
Is there any better way other than create a new array, which is bigger than the old one, then copy the old array to the array?

I would recommend a List<List<int>> for something like this, unless you have a reason not to.
The code for it may look something like this:
List<List<int>> my2dList = new List<List<int>>()
{
new List<int>()
{
1,
2,
3
},
new List<int>()
{
4,
5,
6
},
};
my2dList.Add(new List<int>(){7,8,9});
Alternatively, if you really want to limit each column to a length of three, consider using an inner structure with an immutable size (array of size 3, etc)

It seems like you might want to use a different data structure, a list of arrays would make this much easier.

Extended version of the code snippet posted by #VP. includes the back-conversion from List(List> to Jagged Array using Linq:
// 2d array to List
List<List<int>> ar2list = new List<List<int>>()
{
new List<int>() { 1, 2, 3 },
new List<int>() { 4, 5, 6 },
};
// adding item to List
ar2list.Add(new List<int>() { 7, 8, 9 });
// List to Jagged array conversion using Linq
int[][] _arrConcat = ar2list.Select(Enumerable.ToArray).ToArray();
Finally, pertinent to this particular use-case as requested by OP, int[][] can be easily converted to int[,] with simple for loop:
array2d = new int[_arrConcat.Length, 3];
for (int i = 0; i<_arrConcat.Length; i++)
{
for (int j = 0; j < 3; j++)
{
array2d[i, j] = _arrConcat[i][j];
}
}
where array2d is the original array with added index/content.
Hope this will help. Best regards,

Related

How can change two 1d list array to 2 dimensional list array?

List<int> Boxsize = {3,1,6,7}
List<int> Boxunit = {2,7,4,9}
List<List<int>> Allbox = new List<List<int>>();
I try to make 2-dimensional list as like each element (Boxsize[i], Boxunit[i])
because Boxsize, Boxunit will variable
ex.
List<List<int>> Allbox = {{3,2} , {1,7} , {6,4} , {7,9}}
for (int i = 0; i < Boxsize.Count; i++)
{
Allbox[i].Add(Boxunit[i]);
Allbox[i].Add(Boxsize[i]);
}
It doesn't work, and I am getting an ArgumentOutOfRangeException.
Would you help me this?
You can simply initialize the nested list item inside the for.
var innerList = new List<int>();
innterList.Add(Boxunit[i]);
innterList.Add(Boxsize[i]);
Allbox.Add(innerList);
You could, though just use a Dictionary or a custom class.
Using dictionary instead of list may be more useful.
List<int> Boxsize =new() { 3, 1, 6, 7 };
List<int> Boxunit =new() { 2, 7, 4, 9 };
Dictionary<int, int> s = new();
for (int i = 0; i < Boxsize.Count; i++)
{
s.Add(Boxsize[i], Boxunit[i]);
}

How to initialize a multidimensional array

My problem is I want to initialize a multidimensional array declared like this:
int[][][] my3DArray;
However, the following code gives me an error on [sizeY][sizeZ] saying it expected ',' or ']'.
void Set3DArraySize(int sizeX, int sizeY, int sizeZ)
{
my3DArray = new int[sizeX][sizeY][sizeZ];
}
When i declare the array like this though:
int[,,] my3DArray;
I am able to initialize it without any problems by doing it like this:
my3DArray = new int[sizeX,sizeY,sizeZ];
But then the problem becomes that if I try to get the length of one of the arrays I can't do for example my3DArray[x,y].Length and am instead forced to pass all of the indexes together my3DArray[x,y,z].
So, is there any way I can initialize the array with it being declared as int[][][] my3DArray;? Or will I have to store the sizes of the arrays elsewhere and use it like this int[,,] my3DArray;?
You can do:
new int[][][] myArray = new int[][][]
{
new int[][]
{
new int[]
{
// Your numbers
}
}
}
myArray[0].Length
myArray[0][0].Length
myArray[0][0][0].Length
Works fine
int[][] is a jaggad array, which means that every array can be in a different size.
This is why you can initialize it that way:
int[][] arr2D= new int[3][];
arr2D[0] = new int[0];
arr2D[1] = new int[1];
arr2D[2] = new int[2];
which will create a 2d array that looks like this:
_
_ _
_ _ _
The following is an example to create 3d jaggad array (with different sizes for each dimension- 5 rows, 3 columns and 6 depth):
int[][][] arr3D = new int[5][][];
for (int col = 0; col < arr3D.Length; col++)
{
arr3D[col] = new int[3][];
for (int depth = 0; depth < arr3D[col].Length; depth++)
{
arr3D[col][depth] = new int[6];
}
}
In order to get the dimension size in jaggad array, you can simply get the lenth of the array, but keep in mind that if the array is actually jagged, you will have different sizes for different arrays. if you initialize all of the arrays in a specific dimension with the same value, than you can check either of them, it will be the same.
int[,] is a multi dimensional array that every dimension have a fixed size.
To create a multi dimensional:
int[,] arr2D = new int[3,4];
which will create a 2d array looking like this:
_ _ _ _
_ _ _ _
_ _ _ _
In multi dimensional array you can't change the length of a specific row or column.
In most cases you will probably prefer a multi dimensional array.
In order to get the size of a specific dimension in a multi dimensional array, you can use the following method:
int rows = arr22.GetLength(0); int cols = arr22.GetLength(1); int depth = arr22.GetLength(2);
The input is the dimension you want the size of.
You can't declare a jagged array in one line like this: new int[sizeX][sizeY][sizeZ]; as you really have three levels of nested arrays. You need to initialize them at each level.
This is what that would look like:
void Set3DArraySize(int sizeX, int sizeY, int sizeZ)
{
my3DArray = new int[sizeX][][];
for (var x = 0; x < sizeX; x++)
{
my3DArray[x] = new int[sizeY][];
for (var y = 0; y < sizeY; y++)
{
my3DArray[x][y] = new int[sizeZ];
}
}
}
Now, if you do want to initialize a multidimensional array, you can do this:
int[,,] z =
{
{ { 1, 2, }, { 1, 2, }, { 1, 2, }, },
{ { 1, 5, }, { 1, 5, }, { 2, 8, }, },
{ { 1, 5, }, { 1, 5, }, { 2, 8, }, },
{ { 1, 5, }, { 1, 5, }, { 2, 8, }, },
};
And then, to get the dimensions, you can do this:
Console.WriteLine(z.GetLength(0));
Console.WriteLine(z.GetLength(1));
Console.WriteLine(z.GetLength(2));
That gives me:
4
3
2
It's important to note that with a jagged array each nested array can be of different length, but with a multidimensional array then each dimension must be uniform.
For example, a jagged array could look like this:
int[][] y = new int[][]
{
new [] { 1, 2, },
new [] { 1, 2, 3, },
new [] { 1, },
};
And a multidimensional array like this:
int[,] y =
{
{ 1, 2, 3, },
{ 4, 5, 3, },
{ 1, 6, 3, },
{ 1, 7, 8, },
};
I could not do this:
//illegal!!!
int[,] y =
{
{ 1, 2, 3, },
{ 4, 5, 3, 7, },
{ 1, 6, },
{ 1, 7, 8, },
};
First,
int[][][]
is a jagged array, or an array of arrays of arrays. Where as,
int [,,]
is a multi-dimensioinal array. A single array with many dimensions.
While multi-dimensional arrays are easier to instantiate and will have fixed dimensions on every axis, historically, the CLR has been optimized for the vastly more common case of single dimensional arrays, as used in jagged arrays. For large sizes, you may experience unexpected performance issues.
You can still get the dimensions of a multi-dimensional array by using the GetLength method, and specifying the dimension you are interested in but, its a little clunky.
The number of dimensions can be retrieved from the Rank property.
You may prefer a jagged array and instantiating one axis at a time.
To instantiate jagged arrays, see this Initializing jagged arrays.
void Set3DArraySize(int sizeX, int sizeY, int sizeZ)
{
my3DArray = Enumerable.Repeat(Enumerable.Repeat(new int[sizeZ], sizeY).ToArray(),sizeX).ToArray();
}

two dimension array; one dimension length is defined one is undefined in c#

I want to make an array which one dimension's length is defined but the other one is undefined
I try to do it with "LIST" and I dont know how to make a two dimension array which I already know how much is the length of one dimension
Make an array of lists. But make sure you include System.Collections.Generic in your class:
using System;
using System.Collections.Generic;
in the body of the method or class where you need this:
var arrayOfList = new List<int>[10];
for (var i = 0; i < 10; i++)
{
// initialize each entry of the array
arrayOfList[i] = new List<int>();
}
// add some stuff to entry one at a time
arrayOfList[0].Add(1);
// add some integers as a range
arrayOfList[0].AddRange(new [] {2, 3, 4});
// add some stuff to entry 1
arrayOfList[1].AddRange(new [] {5, 6});
If you don't want to use the generic list class, you can do a jagged array but it isn't as nice to deal with.
int[][] jaggedArray = new int[3][];
// initialize before using or else you'll get an error
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
// populate them like this:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
See more here: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Compact an Array function in C#

How can I make a Function to compact an array with duplicate entries?
For example!
A function that will take a sorted array of integers and return the array compacted. That is, given an array containing: 1, 2, 6, 8, 8, 8, 9, 10, 10, when the function returns, the contents of the array should be: 1, 2, 6, 8, 9, 10.
This is NOT hw. I am trying to make a function that will do this.
How about:
array = array.Distinct().ToArray();
or, as a function:
private int[] RemoveDuplicates(int[] array)
{
return array.Distinct().ToArray();
}
then call it with:
array = RemoveDuplicates(array);
extension methods:
public static T[] RemoveDuplicates<T>(this T[] array)
{
return array.Distinct().ToArray();
}
public static List<T> RemoveDuplicates<T>(this List<T> list)
{
return list.Distinct().ToList();
}
using for array:
int[] array = new[] {1, 3, 4, 3};
array = array.RemoveDuplicates();
using for list:
List<int> list = new List<int> {1, 3, 4, 3};
list = list.RemoveDuplicates();
The most straightforward way is probably with Linq
array = array.Distinct().ToArray()
However, Linq is not always the fastest approach.
If you do not wish to use Linq, you can do something like this (untested, but close)
List<int> compacted = new List<int>();
// If array is not a local variable:
// Assign to a variable to avoid re-evaluating the property every loop iteration
// Otherwise use array.Length as the loop termination condition to enable array
// bounds check elimination. Thanks #Harold for the insight
// http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx
int max = array.Length;
int last = 0;
for (int i=0; i < max; i++)
{
if (i == 0)
{
compacted.Add(array[i]);
last = array[i];
}
else
{
if (array[i] != last) compacted.Add(array[i]);
last = array[i];
}
}
array = compacted.ToArray();

Reversing order of elements in multidimensional array

I have an array with elemnents in order 1,2,3,4,5 and I would need to reverse it so it will be 5,4,3,2,1.
What about the following pseudo code? Is here not an easier way
EDIT: I Am sorry I thought multidimensional array
someclass [,] temporaryArray=new someclass [ArrayLenght,ArrayLenght];
//for each dimension then
for(int I=0;I<ArrayLenghtOfDimension;I++)
{
temporaryArray[ArrayLenghtOfDimension-I]=Array[I];
}
Array=temporaryArray;
The array base class has a Reverse() extension method built in
int[] originalArray = new int[] { 1, 2, 3, 4, 5 };
int[] reversedArray = originalArray.Reverse().ToArray();
Note that the Reverse method returns IEnumerable, so you need to call ToArray() on the result.
And if you need to just iterate over the elements in the array, then all you need is
foreach (int element in originalArray.Reverse())
Console.WriteLine(element);
Oops - Reverse is on IEnumerable, not Array, so you can use that with any collection.
IEnumerable<int> IEnumerableInt = new List<int>() { 1, 2, 3 };
int[] reversedArray2 = IEnumerableInt.Reverse().ToArray();
Yes there is fast solution exists in .net
int[] values = new int[] { 1, 2, 3, 4, 5 };
Array.Reverse(values);
Your array is reversed. so you can iterate through it
foreach (int i in values)
{
Response.Write(i.ToString());
}
the above code will display
54321
It will also work for string[], char[] or other type of arrays
Event though the Array class has Reverse methods defined:
Array.Reverse(originalArray); // original array is now reversed
If all you need to do is iterate backwards over it do the following:
for(int I= ArrayLength - 1; I >= 0; I--)
{
}
This avoid re-allocating memory for the reversed array.
Array.Reverse is the best way to do this. Do you care about order of the elements at all? If so,then you can do the following.
int[] originalArray = new int[] { 10, 2, 13, 4, 5 };
int[] descOrderedArray = originalArray.OrderByDescending(i => i).ToArray();
int[] ascOrderedArray = originalArray.OrderBy(i => i).ToArray();
For a multi-dimensional array it's the same idea
int[][] multiDimArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 } };
int[][] reversedMultiArray = multiDimArray.Reverse().ToArray();
produces an array of two arrays that is: {4, 5, 6}, {1, 2, 3}

Categories

Resources