C# 3 dimensional array - c#

I want to store ARRAY from 3 dimensional array into buildingCostIds, but it says I MUST have 3rd number.
public static int[, ,] buildingCost = { {{0,1,2},{5,5,5}}};
public static void addBuilding(int[] ids, int[] amounts, int buildingId)
{
int[] buildingCostIds = buildingCost[buildingId, 0, *];
}
*I need third number here, but I don't want it because it will extract just number, I want whole array!
PROBLEM SOLVED, solution:
public static Array extractArray(int dim1, int dim2)
{
int[] tempArray = { };
for (int number=0;number<=2; number++)
{
tempArray[number] = buildingCost[dim1, dim2, number];
}
return tempArray;
}

This might be simpler if you use an array-of-arrays, or jagged array [][][] like
int[][][] buildingCost = new int[2][][];
Then you can access buildingCost[buildingId, 0] which is an array of ints.
There is a related question here
EDIT
Be aware the "problem solved" you added to the question duplicates the data, so you may run out of memory if you keep doing this.
Consider using a List of Lists of Lists and lazy evaluating what you need.

Try This
int[, ,] array3D = new int[3,3,3]

Related

How to find N highest numbers in array?

I needed to write a function that finds N highest numbers in an array.
I tried nothing. Don't even know where to start.
public int marathon(int input1,int input2, int[] input3)
{
// this is the function, ignore first input its not relevant input 2 is
// N(How much highest numbers you want from array )
}
If you put 2 as input2 and array looks like this {1,2,3,4} output will be 3 and 4
A little lambda will do the trick.
var top = new[] { 1, 2, 3, 4 }.OrderByDescending(num => num).Take(N);
By LINQ: Simply sort the array and take the first N items. Example of an extension method to do that:
public static class ExtensionMethods
{
public static IEnumerable<T> TakeHighests<T>(this IEnumerable<T> collection, int count)
{
return collection.OrderByDescending(i => i) // Sort the enumerable (arrays are also enumerables). Use OrderBy() for N lowest items
.Take(count) // Take only `count` items
}
}
Sample using of taking 2 highest values:
int[] arr = ...;
int[] twoHighests = arr.TakeHighests(2).ToArray();

Accessing arrays dynamically

I'm working on a project. I've a situation here. I'm having arrays with similar names consider arr1, arr2, arr3, etc.
Now I know the array number which I'm supposed to use let it be 2. Is there any way in c# to make the array name dynamically through strings and use it.
Like in flash action script we can do
_root["arr"+i][0]
here i contains the array number to be used.
No - you cannot access variable names dynamically. You can use reflection to dynamically access properties, but not variables. I would use a List<int[]> like so:
List<int[]> arrList = new List<int[]> {arr1, arr2, arr3);
int[] arr = arrList[i-1]; // since lists and arrays use 0-based indexes
You can use a dictionary:
var dictionary = new Dictionary<string, int[]>();
dictionary.Add("array1", arr1);
dictionary.Add("array2", arr2);
dictionary.Add("array3", arr3);
var arr = dictionary[string.Format("array{0}", i)];
What you want is something what JavaScript or dynamic languages have, but their array types are rather associative arrays. To reach the functionality you want you can use Dictionary:
var arr1 = new int[] { 0, 1, 2, 3 };
var arr2 = new int[] { 0, 1, 2, 3 };
var arr3 = new int[] { 0, 1, 2, 3 };
var _root = new Dictionary<string, int[]>();
_root.Add("arr1", arr1);
_root.Add("arr2", arr2);
_root.Add("arr3", arr3);
for (int i = 1; i <= 3; i++)
{
int arrElem = _root["arr" + i][0];
}
Note the expression within the for loop, it's like what you were asking for.
use list for performing dynamic operations
As suggested in other answers the way to achieve the dynamism you're looking for is to put all of the arrays in a collection ( List<int[]> ) and then you can write more generalized code which operates on the contents of a given array without knowing which array it's operating on at compile time.

c# Leaner way of initializing int array

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?
int nums=5;
int[] array= new int[nums];
for(int i=0;i<num;i++)
{
array[i] = i;
}
Maybe with linq or some array.function?
int[] array = Enumerable.Range(0, nums).ToArray();
Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;
int[] array = Enumerable.Range(0, nums).ToArray();
Generates a sequence of integral numbers within a specified range.
Using Enumerable.Range
int[] array = Enumerable.Range(0, nums).ToArray();
Maybe I'm missing something here, but here is the best way I know of:
int[] data = new int [] { 383, 484, 392, 975, 321 };
from MSDN
even simpler:
int[] data = { 383, 484, 392, 975, 321 };

fill 3-dimensional array(jagged array) with point data

I do have a 3-dimensional matrix
private int[][][] Matrix
but I dont know how to fill this.
the first dimension is for my slices of a picture
the second for my x-values of one slice ad the 3rd slice for my y-values.
so das anybody know how to fill this arrays with some data for testing?
thanks
You can do something like this:
Matrix = new int[5][][]; // 5 slices
Matrix[0] = new int[3][]; // 3 x values for the first slice
Matrix[0][0] = new int[2]; // 2 y values for the first x value in the first slice
But I don't think that you should use something like this. It is very error prone.
I suggest something like this:
class Slice
{
public IList<XValue> XValues {get; set; }
}
class XValue
{
public IList<YValue> YValues {get; set; }
}
class YValue
{
// ...
}
var slices = new List<Slice>();
You can use array literals to create arrays of arrays of arrays:
private int[][][] Matrix = {
{
{1,2,3},
{4,5}
},
{
{1,2},
{3},
{4,5,6,7,8},
{9,10}
},
{
{1,2,3}
}
};
Note that this is a jagged array, so different subarrays can have different number of items. If you want a three dimensional matrix you might want the three dimensional array int[,,] instead of nested one dimensional arrays.

How to copy part of an array to another array in C#?

How can I copy a part of an array to another array?
Consider I'm having
int[] a = {1,2,3,4,5};
Now if I give the start index and end index of the array a it should get copied to another array.
Like if I give start index as 1 and end index as 3, the elements 2, 3, 4 should get copied in the new array.
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
a = source array
1 = start index in source array
b = destination array
0 = start index in destination array
3 = elements to copy
See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().
A purportedly faster extension method is described here.
int[] a = {1,2,3,4,5};
int [] b= new int[a.length]; //New Array and the size of a which is 4
Array.Copy(a,b,a.length);
Where Array is class having method Copy, which copies the element of a array to b array.
While copying from one array to another array, you have to provide same data type to another array of which you are copying.
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
In C# 8+ you can use ranges.
int a[] = {1,2,3,4,5};
int b[] = a[1..4]; // b = [2,3,4];
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}

Categories