Multidimensional array init without pre-existing values? - c#

How can we initialize a multidimensional array without pre-existing values? Only the third one is correct, but it works with pre-existing values. I would like my multidimensional array to contain 10 or 20 values, and add them later on with numbers[y][x] :
int[][] numbers = new int[10][];
//List<int[]> numbers = new List<int[]>();
//int[10][]{ new int[]{}};
//correct : { new int[] {1, 2}, new int[] {3, 4, 5} };
numbers[0][0] = 58;
Would you know how to do this? (I don't know if [,] is the same as [][] by the way)
Thanks

Would you know how to do this? (I don't know if [,] is the same as [][] by the way)
there are not the some as int[][] test = new int[10][]; is called a jagged array (array of arrays) and int[,] is a fixed array
just declare your array as the following
int[,] test = new int[10,30];
test[0,1] = 10;
test[1,2] = 20;

You can try initiating values this way, it is one way to create jagged-array
int[][] test = new int[10][];
test[0] = new int[20];
test[1] = new int[30];
test[2] = new[] { 3, 4, 5 };
test[0][1] = 10;
test[1][2] = 20;

Related

Populating an array with elements [duplicate]

Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}

Is there any way to create or declare arrays automatically?

The arrays depending on the user input.
for example:
int n;//from the user
for(i=1;i<=n;i++)
{
int[] arr + i = new int[5];
}
that means create 4 arrays (n=4):
array1
array2
array3
array4
how can I create? Is there any method?
It really depends on what exactly you are trying to do. For your example, you could try using a list of arrays. Whenever you need a new array, add a new array to the list.
List<int[]> arrays = new List<int[]>();
for(int i = 0; i < n; i++) {
arrays.Add(new int[5]);
}
To access a specific array in the list you can do
arrays[42]
To do something with all of the arrays, you can use a foreach loop:
foreach(var array in arrays) {
array[0] += 42;
}

Having trouble initialising an array of a custom class

Here's the code:
public class RhombMap
{
private Vector3 size;
private Rhomb[][][] map;
public RhombMap( int sizeX, int sizeY, int sizeZ )
{
size = new Vector3 (sizeX, sizeY, sizeZ);
Rhomb[][][] map = new Rhomb[sizeX] [sizeY] [sizeZ];
}
}
Which is annoyingly giving me the error:
Assets/Scripts/MapController.cs(186,46): error CS0021: Cannot apply indexing
with [] to an expression of type `Rhomb'
I'm not trying to index it, I'm trying to initialise an array of it, using exactly the same syntax as in Microsoft's own tutorial.
Can anyone spot what is, hopefully, a glaring error?
There's a difference between 3d array which you can initialize in one go:
Rhomb[,,] map = new Rhomb[sizeX, sizeY, sizeZ];
and jagged array (array of array of array) where you have to create each of the inner arrays:
Rhomb[][][] map = Enumerable
.Range(0, SizeX)
.Select(x => Enumerable
.Range(0, SizeY)
.Select(y => new Rhomb[SizeZ])
.ToArray())
.ToArray();
Please, notice, that you've redeclared map as a local variable within RhombMap constructor
Edit: diffrence between 2d array (let me not put 3d) and jagged one illustrated:
// 2d: always rectangle (2x3 in this case - 2 rows each of 3 items)
// that's why when been initializing wants just width and height
int[,] arr2d = new int[,]
{{1, 2, 3}
{4, 5, 6}};
// width and hight
int[,] arr2d_empty = new int[2, 3];
// jagged: all rows (subarrays) are of arbitrary lengths
// that's why when been initializing wants all rows been initialized individually
int[][] jagged = new int[][] {
new int[] {1, 2, 3, 4}, // 4 items
new int[] {5}, // 1 item
new int[] {6, 7, 8}, // 3 items
};
// each line (subarray) must be specified
int[][] jagged_empty = new int[][] {
new int[4],
new int[1],
new int[3],
};
private Rhomb[][][] map;
...
Rhomb[][][] map = ...
You've declared a new variable with the same name.
Additionally, as you've declared an array-of-arrays, you can't one-line create a new instance. You can either use one of Dmitry's solutions or do it this way:
map = new Rhomb[sizeX][][];
for(int x = 0; x < sizeX; x++) {
map[x] = new Rhomb[sizeY][];
for(int y = 0; y < sizeY; y++) {
map[x][y] = new Rhomb[sizeZ];
}
}
I still think Dmitry's solution of declaring your array as Rhomb[,,] would be best, though.

Random number generator choosing only between given few numbers in C#

I know how to choose random numbers between two numbers. However I don't know how to make it to choose a random number that I tell it.
This is what I am trying to do. I have 5 integers.
int Hamburger = 5;
int Sandwich = 7;
int ChickenSalad = 10;
int Pizza = 15;
int Sushi = 20;
5,7,10,15,20 are the prices of each food and I want to make it so that it would choose a random number from these chosen numbers. 5,7,10,15,20.
I am new to C# so I don't really know much about this. I found this
randomNoCorss = arr[r.Next(arr.Length)];
in another post but I don't understand it and I don't know how I can put it in my code.
You have to create an array of your possible values and then randomly generate an index for that array:
int Hamburger = 5;
int Sandwich = 7;
int ChickenSalad = 10;
int Pizza = 15;
int Sushi = 20;
Random r = new Random();
var values = new[] { Hamburger, Sandwich, ChickenSalad, Pizza, Sushi };
int result = values[r.Next(values.Length)];
What this does is it takes all of your given values and places them inside an array. It then generates a random integer between 0 and 4 and uses that integer to get a value from the array using the generated integer as the array's index.
Full code is:
Random r = new Random();
int[] priceArray = new int[] { 5, 7, 10, 15, 20 };
int randomIndex = r.Next(priceArray.Length);
int randomPrice = priceArray[randomIndex];
You need to add your values in an array and then you can choose a random number from that array
int[] myNumbers = new int[] { 5, 7, 10, 15, 20 };
var random = new Random();
var numberResult = myNumbers[random.Next(5)];
You can do this in LINQ:
int[] intArray = new int[] { 5, 7, 10, 15, 20 };
int result = intArray.OrderBy(n => Guid.NewGuid()).Select(x => x).Take(1)
.SingleOrDefault();
The result will be random based on your declared array of integers in variable intArray.
Or you can do this by getting the random index of your array:
int[] intArray = new int[] {5, 7, 10, 15, 20 };
Random rndom = new Random();
int index = rndom.Next(0, intArray.Length - 1); //Since int array always starts at 0.
int intResult = intArray[index];
Let me know if you need more clarifications.

What are jagged arrays good for? [duplicate]

What is a jagged array (in c#)? Any examples and when should one use it....
A jagged array is an array of arrays.
string[][] arrays = new string[5][];
That's a collection of five different string arrays, each could be a different length (they could also be the same length, but the point is there is no guarantee that they are).
arrays[0] = new string[5];
arrays[1] = new string[100];
...
This is different from a 2D array where it is rectangular, meaning each row has the same number of columns.
string[,] array = new string[3,5];
A jagged array is the same in any language, but it's where you have a 2+ dimensional array with different array lengths in the second and beyond array.
[0] - 0, 1, 2, 3, 4
[1] - 1, 2, 3
[2] - 5, 6, 7, 8, 9, 10
[3] - 1
[4] -
[5] - 23, 4, 7, 8, 9, 12, 15, 14, 17, 18
Although the best answer is chosen by the question owner but still I want to present the following code to make jagged array more clear.
using System;
class Program
{
static void Main()
{
// Declare local jagged array with 3 rows.
int[][] jagged = new int[3][];
// Create a new array in the jagged array, and assign it.
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[0][1] = 2;
// Set second row, initialized to zero.
jagged[1] = new int[1];
// Set third row, using array initializer.
jagged[2] = new int[3] { 3, 4, 5 };
// Print out all elements in the jagged array.
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write(innerArray[a] + " ");
}
Console.WriteLine();
}
}
}
The output will be
1 2
0
3 4 5
Jagged arrays are used to store data in rows of varying length.
For more information check this post at MSDN blog.
You can find more information here : http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Also :
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
or
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
A jagged array is one in which you declare the number of rows during declaration but you declare number of columns during run time or also by user choice,simply its mean when you want different number of columns in each JAGGED array is suitable in that case
int[][] a = new int[6][];//its mean num of row is 6
int choice;//thats i left on user choice that how many number of column in each row he wanna to declare
for (int row = 0; row < a.Length; row++)
{
Console.WriteLine("pls enter number of colo in row {0}", row);
choice = int.Parse(Console.ReadLine());
a[row] = new int[choice];
for (int col = 0; col < a[row].Length; col++)
{
a[row][col] = int.Parse(Console.ReadLine());
}
}
Jagged array is an array with other arrays contained within.
A jagged array is a array in which the number of rows is fixed but the number of column is not fixed.
Code for jagged array in C# for window form application
int[][] a = new int[3][];
a[0]=new int[5];
a[1]=new int[3];
a[2]=new int[1];
int i;
for(i = 0; i < 5; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 3; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 1; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
As you can see in the above program no of rows is fixed to 3, but the number of columns is not fixed. So we have taken three different value of columns i.e. 5, 3 and 1. The ListBox1 keyword used in this code is for the listbox that we will use in the window form to see the result by the click of button which will be also used in the window form. All the programming done here is on the button.
Jagged Array is multidimensional array with different different number of rows.

Categories