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];
}
}
Related
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];
}
}
I have the following code, which creates a 2D array in a nested loop, What I want to do is to create this 2D array each iteration but with name concatenated to "j" value . For example,
In first iteration the result will be : double[,] visualmatrix1.
I tried to put +j but it fails.
ExtractDescriptorsForm ex = new ExtractDescriptorsForm(65,10);
int a = ex.m_maxExtract;
for (int i = 0; i < m_descriptor.visualword.Length; i++)
{
for (int j = 0; j < a; j++)
{
double[,] visualmatrix = new double[m_descriptor.visualword.Length, 2];
visualmatrix[i, 0] = m_descriptor.visualword[i].identifier;
visualmatrix[i, 1] = (m_descriptor.visualword[i].tf) * (m_descriptor.visualword[i].idf);
}
}
Since your code lost the new-created array inside the loops, you should use a list to store the 2D arrays.
List<double[,]> arrays = new List<double[,]>();
ExtractDescriptorsForm ex = new ExtractDescriptorsForm(65,10);
int a = ex.m_maxExtract;
for (int i = 0; i < m_descriptor.visualword.Length; i++)
{
for (int j = 0; j < a; j++)
{
double[,] visualmatrix = new double[m_descriptor.visualword.Length, 2];
visualmatrix[i, 0] = m_descriptor.visualword[i].identifier;
visualmatrix[i, 1] = (m_descriptor.visualword[i].tf) * (m_descriptor.visualword[i].idf);
arrays.Add(visualmatrix);
}
}
Then access it by
arrays[n]
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]));
I have a multidimensional double array with any number of rows and columns:
var values = new double[rows, columns];
I also have a list of double arrays:
var doubleList = new List<double[]>();
Now, I would like to add each column in the multidimensional array to the list. How do I do that? I wrote this to illustrate what I want, but it does not work as I am violation the syntax.
for (int i = 0; i < columns; i++)
{
doubleList.Add(values[:,i];
}
var values = new double[rows, columns];
var doubleList = new List<double[]>();
for (int i = 0; i < columns; i++)
{
var tmpArray = new double[rows];
for (int j = 0; j < rows; i++)
{
tmpArray[j] = values[j, i];
}
doubleList.Add(tmpArray);
}
You will need to create a new array for each column and copy each value to it.
Either with a simple for-loop (like the other answers show) or with LINQ:
for (int i = 0; i < columns; i++)
{
double[] column = Enumerable.Range(0, rows)
.Select(row => values[row, i]).ToArray();
doubleList.Add(column);
}
With the approach you were taking:
for(int i = 0; i != columns; ++i)
{
var arr = new double[rows];
for(var j = 0; j != rows; ++j)
arr[j] = values[j, i];
doubleList.Add(arr);
}
Build up the each array, per row, then add it.
Another approach would be:
var doubleList = Enumerable.Range(0, columns).Select(
i => Enumerable.Range(0, rows).Select(
j => values[j, i]).ToArray()
).ToList()
Which some would consider more expressive in defining what is taken (values[j, i] for a sequence of i inner sequence of j) and what is done with them (put each inner result into an array and the result of that into a list).
static void Main(string[] args)
{
char[][] array = {new char[] {'2','A','3','E'},
new char[] {'F','A'},
new char[] {'F','F','F','F'},
new char[] {'5','A','0','E','9'}};
List<double> arr = new List<double>();
List<double> results = new List<double>();
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < **array.Length**; index++)
{
char c = array[i][index];
if (c > 47 && c < 58)
{
arr.Add(c - 48);
}
else
{
arr.Add((c - 65)+10);
}
}
int power = arr.Count();
for (int ind = 0; ind < power; ind++)
{
arr[ind] = Math.Pow(16, power - 1) * arr[ind];
power--;
result += arr[ind];
}
arr = new List<double>();
results.Add(result);
}
}
My goal is to convert these HEX numeric system numbers to Decimal numeric system numbers.
I know the easy and short way using Console.WriteLine()methods and Standard Numeric Format Strings, but the point is to do this hard way(using jagged arrays). All code work properly , but i dont know how to do change(or get current) value length of different inner arrays in jagged array. If i do it this way usign array.Length - it stay static and doesnt change like i need. I try to use array.GetLength(i) but it dosent work 2.
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < **array.Length**; index++)
To get the required length, try
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < array[i].Length**; index++)
You are checking the length of the outer array (array.Length), while you meant to read the size of the second, inner array (array[i].Length). Try this:
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < array[i].Length; index++)
I would prefer for each
var array = new[]{new[] {'2','A','3','E'},
new[] {'F','A'},
new[] {'F','F','F','F'},
new[] {'5','A','0','E','9'}};
foreach (var item in array)
{
Console.WriteLine(item.Length);
}