Multidimensional Array (2d) of Arrays - c#

I need to make 2d array of arrays.
int[,][] array = new int[n,m][];
for (int i=0; i< m; i++)
{
for (int j=0; j< n; j++)
{
int r = ran.Next(1, 7);
int[] arraybuf = new int[r];
for (int z = 0; z < r; z++)
{
arraybuf[z] = 1;
}
array[i, j] = arraybuf;
Console.WriteLine(array[i, j]);
}
Console.WriteLine();
}
When i'm doing this, console shows
System.Int32[]
in every place where array must be.

Because it is an array. You have an 2D array of arrays of type int.
If you want to display the contents of the array in a specific cell you could do:
Console.WriteLine(string.Join(", ", array[i, j]));

Related

How to read and write data of a 2 dimensional array

I'm making a lotto array game where I'm supposed to write 10 different numbers in to the array and see if I get a bingo. I want it to be 2 dimensional and I have got most of the code right (I have tried it in 1D) but just as I change it to be 2D, I get a problem with the array (array[i]) and I don´t know why.
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kents.lottospel
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int randNum = rand.Next(1, 20);
Console.WriteLine("skriv in nummer");
for(var i= 0; i < 2; i++)
{
for(var j= 0; j < 5; j++)
{
array[i, j] = int.Parse(Console.ReadLine());
if (array[i, j] == randNum) //and this is also
one problem (array[i])
{
Console.WriteLine($"Bing!\nDet rätta talet
var" + " " + randNum);
break;
}
else
{
Console.WriteLine($"tyvärr men du har inte
fått nån bingo denna gången");
}
}
}
Console.WriteLine("skriv in lottoboll nummer" + "
" + i + ":");
Console.WriteLine($"boll nummer" + " " + randNum + " "
+ "gav bingo");
Console.WriteLine("slut på spelet.");
}
}
}
With a two dimensional array, you need two different values to index into it. If you only specify a single value for the index with a 2D jagged array for example, the result will be another array, not a single integer value:
//This will be an int[]
var subArray = array[0]
//This will be an int
var element = array[0][0]
When you are reading input values from the console, you are only specifying one index value for the array so that expression boils down to something like this:
int[] array = new array[5];
array = 42; //compiler error
To populate a 2D array, you will need to change your loop to be a nested one. The outer loop will iterate over the first dimension and the inner loop will iterate over the second dimension:
for(var i = 0; i < 2; i++)
{
for(var j = 0; j < 5; j++)
{
array[i,j] = int.Parse(Console.ReadLine(...));
}
}
The whole point of a 2D array is that it has two dimensions. To access an element, you must specify the index in each dimension. That means that you can't use a single for loop to traverse it either. You generally use two nested for loops, e.g.
for (var i = 0; i <= myArray.GetUpperBound(0); i++)
{
for (var j = 0; j <= myArray.GetUpperBound(1); j++)
{
// Use myArray[i, j] here.
}
}
It's also up to you to make sure that you are consistent with regards to what's a "row" and what's a "column", as they are not explicit in a 2D array.
To be a bit more explicit, here's an example of setting each element in a 2D array and then getting each element:
var myArray = new long[10, 10];
for (var i = 0; i <= myArray.GetUpperBound(0); i++)
{
for (var j = 0; j <= myArray.GetUpperBound(1); j++)
{
myArray[i, j] = DateTime.Now.Ticks;
}
}
for (var i = 0; i <= myArray.GetUpperBound(0); i++)
{
for (var j = 0; j <= myArray.GetUpperBound(1); j++)
{
Console.WriteLine("({0},{1}): {2}", i, j, myArray[i, j]);
}
}

No. of rows 1 less than expected in a jagged array

While printing this jagged array I am getting the no of rows to be 1 less than expected. It should start with 0th index to (h-1)th index creating a total of h rows. What am I doing wrong?
h is the no. of rows.
int h = int.Parse(Console.ReadLine());
int[][] arr = new int[h][];
for(int i = 0; i < h; ++i)
{
arr[i] = new int[i+1];
}
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < i; j++)
{
Console.Write(arr[i][j] + " ");
}
}
That's because your inner for-loop has the condition j < i. If i is 0 in the first pass, the inner for-loop will not be passed.
Try it with
for(int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j] + " ");
}
The arrays have a growing list of elements, starting with 1 so if you want to scan all the items:
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < (i + 1); j++)
{
Console.Write(arr[i][j] + " ");
}
}
Shouldn't it be:
new int[i];
Instead of:
new int[i+1]
Or is it h - 1? Just change that index of the array.
Or you need j < arr[i].Length

Summing a jagged int array in C#

As done here: C # Two-dimensional int array,Sum off all elements, but this time with jagged arrays. Getting:
System.IndexOutOfRangeException.
I am a beginner asking for help. This is my code:
public static int Sum(int[][] arr)
{
int total = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i][j];
}
}
return total;
}
static void Main(string[] args)
{
int[][] arr = new int[][]
{
new int [] {1},
new int [] {1,3,-5},
};
int total = Sum(arr);
Console.WriteLine();
Console.ReadKey();
}
In your inner loop do this instead:
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != null)
{
for (int j = 0; j < arr[i].Length; j++)
{
total += arr[i][j];
}
}
}
return total;
Because your lists aren't even you get the exception on arr.GetLength(1) for the first dimension - it has no item at that place.
The if (arr[i] != null) line is needed in the case the array would look something like:
int[][] arr = new int[][]
{
new int [] {1},
null,
new int [] {1,3,-5},
};
In this case, when we loop with i==1 and try to do arr[i].Length (meaning arr[1].Length we will recieve a NullReferenceException.
And after you do the basics and get to Linq all your current Sum method can be replaced with:
arr.SelectMany(item => item).Sum()
But it is good to start with the basics :)
Since you're using a jagged array the dimensions of that array aren't necessarily even. Have a look at the initialization code of that jagged array:
int[][] arr = new int[][] {
new int [] {1},
new int [] {1,3,-5},
};
So in the first dimension, there are two elements ({1} and {1, 3, -5}). But the second dimension isn't of the same length. The first element has got only one element ({1}) whereas the second element's got 3 elements ({1, 3, -5}).
That's why you're facing the IndexOutOfRangeException.
To fix that, you'll have to adjust the inner loop to the number of elements for that dimension. You can do that like this:
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr[i].Length; j++) {
total += arr[i][j];
}
}

How to convert jagged array to 2D array?

I have a file file.txt with the following:
6,73,6,71
32,1,0,12
3,11,1,134
43,15,43,6
55,0,4,12
And this code to read it and feed it to a jagged array:
string[][] arr = new string[5][];
string[] filelines = File.ReadAllLines("file.txt");
for (int i = 0; i < filelines.Length; i++)
{
arr[i] = filelines[i].Split(',').ToArray();
}
How would I do the same thing, but with a 2D array?
Assuming you know the dimensions of your 2D array (or at least the maximum dimensions) before you start reading the file, you can do something like this:
string[,] arr = new string[5,4];
string[] filelines = File.ReadAllLines("file.txt");
for (int i = 0; i < filelines.Length; i++)
{
var parts = filelines[i].Split(','); // Note: no need for .ToArray()
for (int j = 0; j < parts.Length; j++)
{
arr[i, j] = parts[j];
}
}
If you don't know the dimensions, or if the number of integers on each line may vary, your current code will work, and you can use a little Linq to convert the array after you've read it all in:
string[] filelines = File.ReadAllLines("file.txt");
string[][] arr = new string[filelines.Length][];
for (int i = 0; i < filelines.Length; i++)
{
arr[i] = filelines[i].Split(','); // Note: no need for .ToArray()
}
// now convert
string[,] arr2 = new string[arr.Length, arr.Max(x => x.Length)];
for(var i = 0; i < arr.Length; i++)
{
for(var j = 0; j < arr[i].Length; j++)
{
arr2[i, j] = arr[i][j];
}
}

Printing out a matrix and its transpose, C#

I have a program that creates a transpose 5x8 matrix. I have created an multi dimensional 5x8 array and I also created a new array that hold the transpose of the multi dimensional array. The thing is, I first want to write out the original matrix to the console, and on the same line i want the transpose to be written out. Here is my code:
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[5, 8] {
{ 1, 2, 3, 4, 5,6,7,8 },
{ 9,10,11,12,13,14,15,16},
{ 17,18,19,20,21,22,23,24 },
{ 25,26,27,28,29,30,31,32 },
{ 33,34,35,36,37,38,39,40 },
};
for (int j = 0; j < 8; j++)
{
for (int r = 0; r < 5; r++)
Console.Write("{0} ", matrix[r, j]);
Console.WriteLine();
}
int[,] newArray = new int[8, 5];
for (int j = 0; j < 8; j++)
for (int r = 0; r < 5; r++)
newArray[j, r] = matrix[r, j];
Console.ReadLine();
}
}
what I want is to be shown on the console window is like this:
http://pbrd.co/19SXR0J
but I can only print out the transpose matrix. How do I fix this?
You can just print both lines at a same time, after you computed the transpose.
for (int j = 0; j < 8; j++)
{
//write a line from the first matrix
for (int r = 0; r < 5; r++)
Console.Write("{0} ", matrix[r, j]);
//add some spaces for visual separation
Console.Write("\t\t");
//write a line from the transpose matrix
for (int r = 0; r < 5; r++)
Console.Write("{0} ", newArray[r, j]);
Console.WriteLine();
}

Categories