I am trying to create an array of 6 arrays each containing 4 arrays, each of those 4 arrays with different shape.
Like in the form below:
[[array([[1,2,3,4,6,5],
[5,6,6,7,7,5],
[6,6,5,5,6,5],
[4,6,6,7,7,5],
[5,6,6,7,7,5],
[6,6,5,5,6,5],
[6,6,5,5,6,5],]),
array([[9,9,9],
[9,9,9],
[6,6,6],
[3,3,6],
[6,6,6]]),
array([[6],
[7],
[7],
[7],
[7]]),
array([[7,8,8,8,8]])],
[[array([[1,2,3,4,6,5],
[5,6,6,7,7,5],
[6,6,5,5,6,5],
[4,6,6,7,7,5],
[5,6,6,7,7,5],
[6,6,5,5,6,5],
[6,6,5,5,6,5],]),
array([[9,9,9],
[9,9,9],
[6,6,6],
[3,3,6],
[6,6,6]]),
array([[6],
[7],
[7],
[7],
[7]]),
array([[7,8,8,8,8]])]]
..........
I have this code but I am doing something wrong, I do not get the desired shape.
Can somebody please help me with this?
int populationSize = 6;
double[][][][] population = new double[populationSize][][][];
int value = 3;
for (int i = 0; i < populationSize; i++)
{
population[i] = new double[4][][];
for (int j = 0; j < 4; j++)
{
const int rows = 7, cols = 6;
population[i][j] = new double[rows][];
for (int k = 0; k < rows; k++)
{
population[i][j][k] = new double[cols];
for (int m = 0; m < cols; m++)
{
population[i][j][k][m] = value;
}
}
}
}
const int rows = 7, cols = 6;
population[j][j] = new double[5][];
for (int k = 0; k < rows; k++)
you are using the same indexes for population[j][j], that is probably incorrect.
You are also specifying 7 rows, but create a matrix of size 5. That is probably incorrect.
As Scopperloit points out, you probably want:
const int rows = 7, cols = 6;
population[i][j] = new double[rows][];
for (int k = 0; k < rows; k++)
Overall when debugging problems. Run the code in a debugger and inspect the values against your expectations. Index out of range exceptions are usually very easy to debug:
What is the index?
What is the length of the array?
Is the index or array length incorrect?
I managed to solve my problem.
THis function creates an array of arrays of arrays of different shapes according to another array, and fills it with random normal standard distribution values :
int[,] netshape = new int[,] { { 3, 4}, { 4, 5}, { 4, 1 }, { 1, 4} }; // The shape of the network
public double[][][][] CreateNetwork(int[,] netshape,int populationSize )
{
normal = new MathNet.Numerics.Distributions.Normal(0, 1);// Generate random normal standard distribution
int rows, cols ;
double[][][][] population = new double[populationSize][][][];
for (int i = 0; i < populationSize; i++)
{
population[i] = new double[4][][];
for (int j = 0; j < 4; j++)
{
rows = netshape[j, 0];
cols = netshape[j, 1];
population[i][j] = new double[rows][];
for (int k = 0; k < rows; k++)
{
population[i][j][k] = new double[cols];
for (int m = 0; m < cols; m++)
{
population[i][j][k][m] = normal.Sample(); ;
}
}
}
}
return population;
}
Related
I can't fill it with numbers to 0 - 15 then shuffle the array, so that's not the solution
I used this code in C but now in c# it doesn't work, for some reason this code let some numbers pass the do while.
Random r = new Random();
bool unique;
int rand_num;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
do
{
unique = true;
rand_num = r.Next(16);
for (int k = 0; k < 4; k++)
{
for (int l = 0; l < 4; l++)
{
if (numbers[k, j] == rand_num)
{
unique = false;
}
}
}
} while (!unique);
numbers[i, j] = rand_num;
}
}
}
If the list of possible numbers is small, as in this case, just create the full list and randomise it first, then take the items in the order they appear. In your case, you can put the randomised numbers into a queue, then dequeue as required.
var r = new Random();
var numberQueue = new Queue<int>(Enumerable.Range(0, 16).OrderBy(n => r.NextDouble()));
var numbers = new int[4, 4];
for (var i = 0; i <= numbers.GetUpperBound(0); i++)
{
for (var j = 0; j <= numbers.GetUpperBound(1); j++)
{
numbers[i, j] = numberQueue.Dequeue();
}
}
I suggest you to use the Fisher-Yates algorithm to generate your non-repeatable sequence of random numbers.
It would be very straight-forward to implement a code to fill in a 2d array with those numbers, then.
List<int> seq = Enumerable.Range(0,16).ToList();
int[,] numbers = new int[4,4];
Random r = new();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int n = r.Next(0, seq.Count);
numbers[i,j] = seq[n];
seq.RemoveAt(n);
}
}
The approach you have taken may end up in continuous looping and take lot of time to complete.
Also checking for value in 2D using nested for loop is not efficient.
You can use HashSet to keep track of unique value. Searching in HashSet is fast.
following is the code approach I suggest.
var hashSet = new HashSet<int>();
var r = new Random();
var arr = new int[4, 4];
for(var i = 0;i<4;i++)
{
for(var j = 0;j<4;j++)
{
// Generate random value between 0 and 16.
var v = r.Next(0, 16);
// Check if the hashSet has the newly generated random value.
while(hashSet.Contains(v))
{
// generate new random value if the hashSet has the earlier generated value.
v = r.Next(0, 16);
}
//Add value to the hashSet.
hashSet.Add(v);
// add value to the 2D array.
arr[i, j] = v;
}
}
I hope this will help solving your issue.
The problem with your current approach is that as you get closer to the end of the array, you have to work harder and harder to get the next random value.
Imagine you roll a die, and each time you want to get a unique value. The first time you roll, any result will be unique. The next time, you have a 1/6 chance of getting a number that has already been obtained. And then a 2/6 chance, etc. and in the end most of your rolls will be non-unique.
In your example, you have 16 places that you want to fill with numbers 0 to 15. This is not a case of randomly generating numbers, but randomly placing them. How do we do this with a deck of cards? We shufle them!
My proposal is that you fill the array with unique sequential values and then shuffle them:
Random random = new Random();
int dim1 = array.GetLength(0);
int dim2 = array.GetLength(1);
int length = dim1 * dim2;
for (int i = 0; i < length; ++i)
{
int x = i / dim1;
int y = i % dim1;
array[x, y] = i; // set the initial values for each cell
}
// shuffle the values randomly
for (int i = 0; i < length; ++i)
{
int x1 = i / dim1;
int y1 = i % dim1;
int randPos = random.Next(i, length);
int x2 = randPos / dim1;
int y2 = randPos % dim1;
int tmp = array[x1, y1];
array[x1, y1] = array[x2, y2];
array[x2, y2] = tmp;
}
The shuffle in this code is based on the shuffle found here
int[,] numbers = new int[4, 4];
Random r = new Random();
bool unique;
int rand_num;
List<int> listRandom = new List<int> { };
for ( int i = 0; i < 4; i++ )
{
for ( int j = 0; j < 4; j++ )
{
do
{
unique = false;
if (!listRandom.Contains( rand_num = r.Next( 0, 16 )))
{
listRandom.Add( rand_num );
numbers[i, j] = rand_num;
unique = true;
}
} while ( !unique );
}
}
int[] x = { 1, 2, 3, 4,5 };
int[] y = { 5, 4, 3, 2, 1 };
int[,] s=new int[(x.Length)*(x.Length),2];
for (int i = 0; i < x.Length; i++)
{
for (int j = 0; j < y.Length; i++)
{
s[i, j] = x[i] * y[j];
Console.WriteLine(x[i] + " * " + y[j] + " = " + s[i, j]);
}
}
IndexOutOfRangeException: Index was outside the bounds of the array.
It gives a memory error, but it says it hangs the memory of the variable, but I transfer more than the field of the series. I couldn't figure out what the problem was. Can you help?
IndexOutOfRangeException: Index was outside the bounds of the array.
Change:
for (int i = 0; i < x.Length; i++)
{
for (int j = 0; j < y.Length; i++)
To:
for (int i = 0; i <= x.Length-1; i++)
{
for (int j = 0; j <= y.Length-1; j++)
Also this line:
int[,] s=new int[(x.Length)*(x.Length),2];
Although no big problems but if x[] and y[] are different lengths might cause issues with storing i,j values. Did you mean to declare like :=
int[,] s=new int[(x.Length)*(y.Length),2];
Suppose a have a MxNx3 matrix
byte [,,] myMatrix= new byte[sizeRow, sizeCol, 3];
How do I access a single band of it (for read and write purposes)? Something like:
singleBand = myMatrix[:allRows: , :allCols: , :desiredBand:];
On the left is what I have, of the right is what I want to access (for example).
int M=10;
int N=20;
var test = new byte[3][,] { new byte[N,M],new byte[N,M],new byte[N,M]};
var band1 = test[1]; //its green
band1[2, 2] = 99;
If you can't change the type of myMatrix, then you can use the following code:
byte [,,] myMatrix= new byte[sizeRow, sizeCol, 3];
var singleBand = new byte[sizeRow, sizeCol];
var band = 1;
for (var i = 0; i < sizeRow; i++) {
for (var j = 0; j < sizeCol; j++) {
singleBand[i, j] = myMatrix[i, j, band];
}
}
But if you can change it, then probably Zeromus' solution is better, since you can more easily manipulate with what you call the band.
You simply need to loop through your required array elements and extract the "band" that you need.
// Create a three-dimensional array.
int[, ,] threeDimensional = new int[3, 3, 3];
// Set the first "Band" to 9
threeDimensional[0,0,1] = 9;
threeDimensional[1,0,1] = 9;
threeDimensional[2,0,1] = 9;
threeDimensional[0,1,1] = 9;
threeDimensional[1,1,1] = 9;
threeDimensional[2,1,1] = 9;
threeDimensional[0,2,1] = 9;
threeDimensional[1,2,1] = 9;
threeDimensional[2,2,1] = 9;
// Loop over each dimension's length.
for (int i = 0; i < threeDimensional.GetLength(2); i++)
{
for (int y = 0; y < threeDimensional.GetLength(1); y++)
{
for (int x = 0; x < threeDimensional.GetLength(0); x++)
{
Console.Write(threeDimensional[x, y, i]);
}
Console.WriteLine();
}
Console.WriteLine();
}
Your only option is to access each "cell" in the band one at a time and extract it to some other location. In my case i just put them out to the display.
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'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