I want to get the "Index array" from a multi-dimensional array - c#

I create a multi-dimensional array as follows:
List<int> indexList = GetFromSomewher()
Results = Array.CreateInstance(typeof(System.Double),indexList.ToArray() );
foreach (DataRow row in table.Rows)
{
List<int> indexInstance = new List<int>();
for (int d = 0; d < DegreesOfFreedom; d++)
{
indexInstance.Add(DimDict[d][row.Field<double>(d)]);
}
Results.SetValue(row.Field<double>(DegreesOfFreedom), indexInstance.ToArray());
}
Then, once created I want to see the index array and the value. BUT this only gives me the "value". I can see the index array in debug - but can't access it.
foreach (var res in Results)
{
Console.WriteLine("");
}

Sounds like a job for the humble for loop!
static void Main(string[] args)
{
int[][] test = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
for(int i = 0; i < test.Length; i++)
{
for (int j = 0; j < test[i].Length; j++)
{
Console.WriteLine($"Index: [{i},{j}]: {test[i][j]}");
}
}
}

Related

How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new arrays?

I have to extract pozitiv end negativ numbers from one arrey in two new arrays. How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new arrays?
int[] array = { 12, 23, -22, -823,-4, 351, -999, 62 };
int[] arrayPozitivni = new int [array.Length];
int PozitivniCounter = 0;
for (int i = 0 ; i<array.Length ; i++)
{
if (array[i] < 0 )
{
arrayPozitivni[PozitivniCounter] = array[i];
PozitivniCounter++;
}
}
foreach (var item in arrayPozitivni)
{
Console.WriteLine(item);
}
LINQ can help here to make your life easier:
int[] arrayPositive = array.Where(i => i >= 0).ToArray();
int[] arrayNegative = array.Where(i => i < 0).ToArray();
int[] array = { 12, 23, -22, -823,-4, 351, -999, 62 };
List<int> positiveList= new List<int>();
List<int> negativeList= new List<int>();
for (int i = 0 ; i<array.Length ; i++)
{
if (array[i] < 0 )
{
negativeList.Add(array[i]);
}
else
{
positiveList.Add(array[i]);
}
}
int[] arrayPozitivni = positiveList.ToArray();
int[] arraynegative = negativeList.ToArray();
foreach (var item in arrayPozitivni)
{
Console.WriteLine(item);
}
One good way is to use an ArrayList
using System;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// I have to extract pozitiv end negativ numbers from one arrey in two new arrays.How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new arrays?
int[] array = { 12, 23, -22, -823, -4, 351, -999, 62 };
ArrayList arrayNegative = new ArrayList();
int PozitivniCounter = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] < 0)
{
arrayNegativ.Add( array[i]);
PozitivniCounter++;
}
}
foreach (var item in arrayPozitivni)
{
Console.WriteLine(item);
}
}
}
}

Minimum element of each column in array of arrays

An array of arrays is given. It is necessary to find the minimum element in each column and write the data to a new array. I have done the following implementation, in accordance with the given conditions. But I am having a problem:expected minimum element in each column of the array are incorrect. Where am I making a mistake?
class Program
{
static int[][] Input()
{
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
int[][] a = new int[n][];
//int[] minA = new int[n];
for (int i = 0; i < n; ++i)
{
a[i] = new int[n];
for (int j = 0; j < n; ++j)
{
Console.Write("a[{0},{1}]= ", i, j);
a[i][j] = int.Parse(Console.ReadLine());
}
}
return a;
}
static void Print(int[] a)
{
foreach (double elem in a)
{
Console.Write("{0} ", elem);
}
}
static void Print2(int[][] a)
{
for (int i = 0; i < a.Length; ++i, Console.WriteLine())
for (int j = 0; j < a[i].Length; ++j)
Console.Write("{0,5} ", a[i][j]);
}
static int[] F(int[][] a)
{
int[] b = new int[a[1].Length];
for (int j = 0; j < a[1].Length; j++)
{
int tempmin = a[0][j];
for (int i = 0; i < a[0].Length; i++)
{
if (a[j][i] <= tempmin)
{
tempmin = a[j][i];
b[j] += tempmin;
}
}
}
return b;
}
static void Main()
{
int[][] myArray = Input();
Print2(myArray);
int[] b = new int[myArray.Length];
b = F(myArray);
Print(b);
}
}
I suggest looping over all lines, while tracking all min columns values:
using System.Linq; // for the final `ToArray()`
...
private static int[] MinColumns(int[][] data) {
if (null == data)
throw new ArgumentNullException(nameof(data));
// List of columns' mins; initially the list is empty
List<int> list = new List<int>();
// for each line (not column!) within jagged array...
foreach (int[] line in data) {
// let's just skip null lines (alternative is to throw exception)
if (null == line)
continue;
// each new line can update columns' max values.
// now we update each column
for (int c = 0; c < line.Length; ++c)
// if index c is too big, i.e.
// the line is too long and some columns appear first time...
if (c >= list.Count)
// ...we just add values of such columns as columns' min
for (int i = list.Count; i <= c; ++i)
list.Add(line[i]);
else
// otherwise we update min values: we compare known min and current value
list[c] = Math.Min(list[c], line[c]);
}
// finally, we convert list into array with ahelp of Linq
return list.ToArray();
}
Note, that here we ignore all holes, e.g. for
int[][] demo = new int[][] {
new int[] {1, 2, 3, 4},
new int[] {5, 6}, // <- hole: we don't have 3d and 4th columns here
new int[] {7, 0, 8},
};
the answer will be {Min(1, 5, 7), Min(2, 6, 0), Min(3, 8), Min (4)} = {1, 0, 3, 4}
Edit: Usage is quite direct; something like this (fiddle yourself)
static void Main()
{
// Get jagged array
int[][] myArray = Input();
// Print it
Print2(myArray);
// Get max for each column
int[] b = MinColumns(myArray);
// Print these maxes
Print(b);
}

sum middle number with jagged array in C#

I write some code with jagged array but when i sum middle number program not working and i cant fix it...:
public class JaggedArray
{
public static void Array()
{
int[][] arrayOfArray = ArrayOfArray();
var tong = 0;
for (var i = 1; i < arrayOfArray.Length; i++)
{
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
var bienTam = arrayOfArray[i].Length;
var tamThoi = j;
if (bienTam%2==0&&tamThoi==bienTam/2)
{
tamThoi++;
tong += arrayOfArray[i][tamThoi];
}
}
}
OutPut(arrayOfArray, tong);
}
private static int[][] ArrayOfArray()
{
Random ngauNhien = new Random();
int[][] arrayOfArray = new int[13][];
for (var i = 0; i <arrayOfArray.Length; i++)
{
arrayOfArray[i] = new int[i];
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
arrayOfArray[i][j] = ngauNhien.Next(0, 99); //throw exception
}
}
return arrayOfArray;
}
can someone explain reason why i wrong and how ti fix it?
The problem you are solving is the one Linq is very good for:
int[][] arrayOfArray = new int[][] {
new[] {1, 2, 3}, // 2 is the middle item
new[] {4, 5} // in case of tie, let 5 (right) be the middle item
new[] {7}, // 7
new int[] {}, // should be ignored
};
// 2 + 5 + 7 == 14
var result = arrayOfArray
.Where(line => line != null && line.Length > 0)
.Sum(line => line[line.Length / 2]);
So I've got it compiling:
public class JaggedArray
{
public static void Array()
{
int[][] arrayOfArray = ArrayOfArray();
var tong = 0;
for (var i = 1; i < arrayOfArray.Length; i++)
{
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
var bienTam = arrayOfArray[i].Length;
var tamThoi = j;
if (j % 2 == 0 && j / 2 == bienTam / 2)
{
tamThoi++;
// You need to check here that tamThoi isn't
// outside the bounds of your array
if (tamThoi >= arrayOfArray[i].Length)
{
continue;
}
tong += arrayOfArray[i][tamThoi];
}
}
}
}
private static int[][] ArrayOfArray()
{
Random ngauNhien = new Random();
int[][] arrayOfArray = new int[13][];
for (var i = 0; i < 13; i++)
{
arrayOfArray[i] = new int[i];
// here you're better off using i
// instead of the arrayOfArray[i].Length - because you know the length
for (var j = 0; j < i; j++)
{
arrayOfArray[i][j] = ngauNhien.Next(0, 99);
}
}
return arrayOfArray;
}
}
You can make this far more succinct with LINQ.

Convert multidimensional array to list of single array

I have a multi dimensional array which i need to convert to a list of arrays. Not one single array, but for each iteration of the first dimension i need a separate array containing the values in the second dimension.
How do I convert this:
int[,] dummyArray = new int[,] { {1,2,3}, {4,5,6}};
into a list<int[]> holding two arrays with values {1,2,3} and {4,5,6}?
You can convert 2d array into jagged array and then convert it to List.
int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] jagged = new int[arr.GetLength(0)][];
for (int i = 0; i < arr.GetLength(0); i++)
{
jagged[i] = new int[arr.GetLength(1)];
for (int j = 0; j < arr.GetLength(1); j++)
{
jagged[i][j] = arr[i, j];
}
}
List<int[]> list = jagged.ToList();
You can use Linq:
int[,] dummyArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int count = 0;
List<int[]> list = dummyArray.Cast<int>()
.GroupBy(x => count++ / dummyArray.GetLength(1))
.Select(g => g.ToArray())
.ToList();
You could use for loop like this:
int[,] dummyArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int size1 = dummyArray.GetLength(1);
int size0 = dummyArray.GetLength(0);
List<int[]> list = new List<int[]>();
for (int i = 0; i < size0; i++)
{
List<int> newList = new List<int>();
for (int j = 0; j < size1; j++)
{
newList.Add(dummyArray[i, j]);
}
list.Add(newList.ToArray());
}
Here is a reusable implementation
public static class Utils
{
public static List<T[]> To1DArrayList<T>(this T[,] source)
{
if (source == null) throw new ArgumentNullException("source");
int rowCount = source.GetLength(0), colCount = source.GetLength(1);
var list = new List<T[]>(rowCount);
for (int row = 0; row < rowCount; row++)
{
var data = new T[colCount];
for (int col = 0; col < data.Length; col++)
data[col] = source[row, col];
list.Add(data);
}
return list;
}
}
and sample usage
var source = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
var result = source.To1DArrayList();
Some comments on other answers.
M.kazem Akhgary: If I need a list, I don't see why should I first create jagged array and convert it to a list instead of creating list directly.
Eser: I usually like his elegant Linq solutions, but this definitely is not one of them. If the idea is to use Linq (although I strongly believe it's not intended for that), the following would be much more appropriate:
var source = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
var result = Enumerable.Range(0, source.GetLength(0))
.Select(row => Enumerable.Range(0, source.GetLength(1))
.Select(col => source[row, col]).ToArray())
.ToList();

How to create jagged arrays in c#?

I'm familiar with C. Where I can write like this:
uint array[0xFFFF][20];
But I've no idea how to do this in Csharp. I tried all MS tutorials and other tutorials but no luck.
Can someone please help me out?
Official tutorial. Basically you create the "outer" array first, and then loop trough it, and create each "inner"array individually.
Two examples:
int[][] a = new int[] { new int[]{ 1, 2 }, new int[]{ 3, 4, 5, 6, 7 }};
int[][] c = new int[100][];
for (int i = 0; i < c.length; i++) c[i] = new int[5];
If you need only a 2D rectangular array, you can use int[,] b = new int[10, 7];.
int[][] jaggedArray = new int[3][];
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 };
See Jagged Arrays (C# Programming Guide)
I don't know that in C but in c# you can use jagged arrays like:
// 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();
}
http://www.dotnetperls.com/jagged-array
I think this may help you
static void Main(string[] args)
{
Console.WriteLine("enter the size of rows");
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine("enter the number of elements for row {0}", i + 1);
int x = Convert.ToInt32(Console.ReadLine());
a[i]=new int[x];
for (int j = 0; j < a[i].Length; j++)
{
a[i][j] = Convert.ToInt32(Console.ReadLine());
}
}
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a[i].Length; j++)
{
Console.Write(a[i][j]+"\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
namespace jaggedarray
{
class Program
{
static void Main(string[] args)
{
int[][] jagged = new int[5][];
jagged[0] = new int[4] { 22, 33,44,55 };
jagged[1] = new int[1] { 2 };
jagged[2] = new int[4] { 1, 2, 3, 4 };
jagged[3] = new int[2] { 12,13};
jagged[4] = new int[1] {2};
for (int i = 0; i < jagged.Length; i++ ) {
for (int j = 0; j < jagged[i].Length; j++)
{
Console.Write("\t{0}",jagged[i][j]);
}
Console.WriteLine();
Console.WriteLine();
}
// input jagged array
int [][] arrays=new int[5][];
Console.WriteLine("Please Enter the ValueType to make a jagged array:");
arrays[0] = new int[1];
arrays[1] = new int[2];
arrays[2]=new int [3];
arrays[3]=new int [4];
arrays[4] = new int[5];
for (int i = 0; i < arrays.Length;i++ ) {
for (int j = 0; j < arrays[i].Length; j++)
{
arrays[i][j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("This is jagged array::");
for (int i = 0; i < arrays.Length;i++ ) {
for (int j = 0; j < arrays[i].Length;j++ ) {
Console.Write("\t{0}", arrays[i][j]);
}
Console.WriteLine();
}
}
}
}
creating and displaying element of jagged array
int[][] a = new int[2][];//its mean num of row is 2 which fixed
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());
}
}
//loop for out put the values of jagged array
for (int row = 0; row < a.Length; row++)
{
for (int col = 0; col < a[row].Length; col++)
Console.Write(a[row][col]+"\t");
Console.WriteLine("");
}
here in inserting loop i used
a[row].length
instead of
a.length,
the reason behind is that every row have different number of columns so that way in second loop you have to mentioned the length of each row

Categories