I'm trying to create an array with the following structure
D
C C
B B B
A A A A
Which will be N x N but split diagonally. Initially, all I know is the bottom row essentially just:
string[,] table = new string[n,];
How can I build on this structure so that when I get to the next row I can declare how many elements it has? Would it be something along the lines of:
for(int i = 0; i <= n; i++) {
table[i] = new string[--n]
}
The [,] syntax creates multidimensional arrays, not jagged arrays. For the latter, you would need to do this:
int n = 4;
string[][] table = new string[n][];
for (int i = 0; i < n; i++)
table[i] = new string[n-i];
Btw. you really don’t want to decrement n while looping in a loop with the condition i < n (or i <= n).
Related
I have got 25 elements in my txt file. My code calculates their scores according to answer key. Then i would like to sort them without using sort.Array etc. I made it and a assigned them another array which is name is result. Now i would like to write the elements number according to order of result array
. For example the element 101' score 78. The element 105' s score is 25.
The result array sort them: 78-25
i would like to sort them : 101-105
my code is:
//arranging results according to their values
int temp = 0;
int[] elm = new int[result.Length];
for (int i = 0; i <= result.Length-1 ; i++)
{
for (int j = i+1 ; j < result.Length; j++)
{
if (result[i] < result[j])
{
temp = result[i];
result[i] = result[j];
result[j] = temp;
}
elm[j] = Convert.ToInt16(row[i,0]);
}
;
}
I need to create an array for which I do not know the size in advance. I used the following, but it gives an index out of bounds error in my for -loop.
string[] arr = s.Split('\n');
int[] indices = new int[arr.Length];
string[][] new_arr = new string[arr.Length][];
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].StartsWith("21"))
{
indices[i] = i;
}
}
indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i];
} //first n elements
The error is in the second for-loop. It says
Object reference not set to an instance of an object.
But I did instantiate the string at the beginning?
You just need to initialize each of the arrays within the jagged array:
indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21
// create second-level array
new_arr[0] = new string[indices.Length] ;
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i]; // why 0 here?
}
For a 2 dimensional array, you will have to specify the size of the first dimension. As I see your code, it is using what is called the jagged array (array containing array as elements) and not a pure 2 dimensional array.
var array1 = new int[2,10]; // this is a 2 dimensional array
var array2 = new int[2][]; // this is an array of 2 elements where each element is an `int[]`
As you notice, we don't need to specify the size of the inside element int[]
Now you understand the jagged array, you can see that you are not initializing the inside element, but simply accessing it - and since it is null by default, you hit the exception.
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i];
} //first n elements
In the code above, you should have new_arr[i][0] = arr[i] and also before that line you need to do new_arr[i] = new int[x] where x is teh size that you want for the inside array.
I would like to know how can I check if the sum of every row in 2D array is equal to each other.
Edit: I tired the way Mike suggested but i still got the index out of range. What am I missing?
bool sumSame;
int sum3=0;
int sum4 = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
sum3 += arr[0, i];
}
for (int i = 0; i < arr.GetLength(0); i++)
{
sum4 = 0;
for (int j = 0; j < arr.GetLength(1); i++)
{
**sum4 += arr[i, j];**//The Error is Here
}
if (sum4 != sum3)
{
sumSame = false;
break;
}
}
sumSame = true
You would like to know if all rows in a 2D array have the same sum.
So, you need to write a function which computes the sum of a row.
Then your problem becomes one-dimensional: check whether a function invoked for every element of a one-dimensional array returns the same value for each element. (The fact that an element is in turn another array is irrelevant.)
If you do not want to (or do not know how to) write a function, then you can write the code which computes the sum of a row as a nested loop, (as you already tried to do,) but still, it helps if you conceptually treat these two tasks as completely different from each other, meaning that they should not mix their variables, and the outer loop should only use the result of the calculation of the inner loop.
Generally, the way we make sure that all elements of an array are equal to a certain value is that we compute the value of the first element, (at index 0,) and then we loop for each subsequent element (for( int i = 1; ...) and check whether the value computed for this element is equal to the value that we got for the first element.
You can add the sum of each array to the List<int> and check the number of distinct results with Distinct().Count(), if it's 1 the results are the same for all 2D array.
int[,] arr = new int[,]
{
{1,2,3 },
{3,2,1 },
{2,3,1 }
};
List<int> sums = new List<int>();
for (int i = 0; i < arr.GetLength(0); i++)
{
int sum = 0;
for (int j = 0; j < arr.GetLength(1); j++)
{
sum += arr[i, j];
}
sums.Add(sum);
}
bool sameResults = sums.Distinct().Count() == 1;
I'm new to C# and I can't find an example of this anywhere (although I have seen similar examples but the casting was ToString, whereas in my case I want arrays of integers). I have a DataTable object,
DataTable results = dbCon.ExecuteQuery("my query");
int m = results.Rows.Count;
int n = results.Columns.Count;
I want a jagged array consisting of n one-dimensional arrays (each array being a column of the DataTable (results, in this case).
int[][] jagged = new int[n][];
for (int i = 0; i < n; i++)
{
jagged[i] = new int[m];
//var coli = results.Columns.Cast<Array>().Select(column => Convert.ToInt32(column)).ToArray();
//jagged[i] = coli;
}
I've tried a few things (for example what I commented out) but I'm quite stuck now.
If anyone knows how to do this, please post something! Thanks!
Also, to be more specific, I'd really like to use a function like the one NumPy provides to Python... dataSet = np.array(dataList).astype('float'). Double for loops are not in my best interest as my DataTable is large.
I think you also need to make the array of type object. The DataTable DataRow holds things of type object, therefore that is what you need to store them as in your jagged array.
I think this will work:
DataTable table = dbCon.ExecuteQuery("my query");
int rowCount = table.Rows.Count;
int colCount = table.Columns.Count;
object[][] objs = new object[colCount][];
for (int currentColumn = 0; currentColumn < colCount; currentColumn++)
{
objs[currentColumn] = new object[rowCount];
for (int currentRow = 0; currentRow < rowCount; currentRow++)
{
objs[currentColumn][currentRow] = table.Rows[currentRow][currentColumn];
}
}
I think, you already have this. Try:
results.Rows[rowIndex][columnIndex]
To get it into jagged array, you may go for simple for loop:
for (int i = 0; i < results.Rows.Count; i++)
{
for (int j = 0; j < results.Columns.Count; j++)
{
jagged[i][j] = results.Rows[i][j];
}
}
You can get what you want just using LINQ against the DataTable. For each column in the DataTable, you need to iterate over the rows and select that column. You need to call Cast() to Select() on the columns and AsEnumerable() to be able to Select() on the rows:
int[][] jagged = results.Columns.Cast<DataColumn>()
.Select(
col => results.AsEnumerable()
.Select(row => row.Field<int>(col))
.ToArray()
).ToArray();
I have a 2-dimensional array of objects, which I initialize using the traditional loop:
PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1];
for (int i = 0; i <= LoopCounterMaxValue; i++)
for (int j = 0; j <= LoopCounterMaxValue; j++)
tempPb1[i, j] = new PairDS();
Is there any better way to do this using Enumerable or something?
I thought Initialize could do it, but it only works with value types.
int N = 10;
PairDS[,] temp = new PairDS[N + 1, N + 1];
temp.Initialize();
What I recommend you do is use a jagged array.
class PairDS { public PairDS(int row, int col) { } }
static void Main(string[] args)
{
int N = 10;
PairDS[][] temp = Enumerable.Range(0, N + 1).Select(
(row) => Enumerable.Range(0, N + 1).Select(
(col) => new PairDS(row, col)).ToArray()).ToArray();
}
I don't believe you can represent a multi-dimensional array as an Enumerable or List, directly because it (the CLR) has no way of knowing how you intend to index the array.
If you did work it out row by row, it'd actually be worse (ie slower) then simply looping through the array as you're doing and initializing each cell.
There's no way to directly initialize a 2D array with the Enumerable types and as some users have pointed out there's nothing directly wrong with what you're doing. If you're just looking to simplify the loop though this might be what you're looking for;
const int length = LoopCounterMaxValue + 1;
PairDS[,] tempPb1 = new PairDS[length, lenth];
for (var i = 0; i < length * length; i++) {
var column = i % length;
var row = (i - column) / length;
tempPb1[row, column] = new PairDS();
}