Initializing a jagged array in c# gives index out of range exception - c#

field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < 3; y++)
{
field[x][y] = new int[3];
}
}
For some reason the above code is giving me out of range exception but the following works fine:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
}
for (int y = 0; y < input.Height; y++)
{
for (int x = 0; x < input.Width; x++)
{
field[x][y] = new int[3];
field[x][y][0] = random.Next(0, output.Width);
field[x][y][1] = random.Next(0, output.Height);
field[x][y][2] = MaskFunctions.DSCALE;
}
}
Can anyone point out what am i doing wrong?
Also: Is there a difference between out of range and out of bound exception?

Your inner loop goes from 0 to 3, instead of 0 to input.Height. This will produce an out of range exception when input.Height < 3.
You probably meant to do this:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < input.Height; y++)
{
field[x][y] = new int[3];
}
}

Related

Index out of range for multi dimensional array

I'm getting the error that the index for my array is out of range.
I define a 3D array like this:
Button[, ,] posAr_ItemManager = new Button[maxRows, maxColumns, maxCategories];
Where maxRows, maxColumns and maxCategories are all constant integers.
I then want to loop through this whole array, i do it using nested loops as shown here:
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; i < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; i < posAr_ItemManager.GetLength(2); z++)
{
if (posAr_ItemManager[i,j,z] != null)
{
Button but = posAr_ItemManager[i, j, z];
but.Width = itemWidth;
but.Height = itemHeight;
but.SetValue(Canvas.LeftProperty, itemPanelX + (i + 1) * butSpacing + i * itemWidth);
but.SetValue(Canvas.TopProperty, itemPanelY + (i+1)*butSpacing + i* itemHeight);
}
}
}
}
When I run the program it gives the out of range error where I check if the item is not equal to null.
I have no idea why it does it as I thought my declaration of the 3D array is correct and the nested loop as well? thanks in advance!
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; j < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; z < posAr_ItemManager.GetLength(2); z++)
look very carefully at the middle tests. Also, consider hoisting the GetLength tests so you only do them once per dimension. Perhaps:
int rows = posAr_ItemManager.GetLength(0), columns = posAr_ItemManager.GetLength(1),
categories = posAr_ItemManager.GetLength(2);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
for (int cat = 0; cat < categories; cat++)
You're using "i" to check if the loop is over in each of the dimensions. Change it to corresponded i,j,z.
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; **j** < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; **z** < posAr_ItemManager.GetLength(2); z++)

Limit 2D Array Size on the Console (C#)

Here's my code
public int[,] GetBigEyeRoad(int x)
{
int[,] arrayBigEyeResult = new int[6, x];
Array.Copy(arrayBigEyeRoad, arrayBigEyeResult, arrayBigEyeRoad.GetLength(0) * arrayBigEyeRoad.GetLength(1));
return arrayBigEyeResult;
}
And calling it on my main class like this
int[,] arrayBigEyeRoad = bsb.GetBigEyeRoad(104);
string s = "";
for (int y = 0; y < arrayBigEyeRoad.GetLength(0); y++)
{
for (int x = 0; x < arrayBigEyeRoad.GetLength(1); x++)
{
s += string.Format("{0:D2}", arrayBigEyeRoad[y, x]);
s += ".";
}
s += "\n";
}
Debug.Log(s);
Here on this part
int[,] arrayBigEyeRoad = bsb.GetBigEyeRoad(104);
I only want to display 12 2D array values just like this
int[,] arrayBigEyeRoad = bsb.GetBigEyeRoad(12);
The problem is that it won't let me . Because it will give me an error saying
Destination array was not long enough. Check destIndex and length, and the array's lower bounds
Now how can I possible do it something like this
Limit the 2d display on the console
Pretty simple:
int[,] a1 = new int[100,200];
int[,] a2 = new int[10,5];
for (int i = 0; i < 10; i++)
for (int j = 0; j < 5; j++)
a2[i,j] = a1[i,j];
or
public class MyArray : int[,]
{
public override string ToString()
{
string result = "";
for (int i = 0; i < 10; i++)
for (int j = 0; j < 5; j++)
result += (a1[i,j].ToString() + ",");
return result;
}
}

How to print C# 3D jagged array

From #Henk Holterman's response regarding C# 3 dimensional arrays (answered Mar 29 '09 at 12:05), how do you print foos to the console:
Foo[][][] foos = new Foo[2][][];
for (int a = 0; a < foos.Length; a++)
{
foos[a] = new Foo[3][];
for (int b = 0; b < foos[a].Length; b++)
{
foos[a][b] = new Foo [4];
for (int c = 0; c < foos[a][b].Length; c++)
foos[a][b][c] = new Foo();
}
}
Thanks.
This is fairly simple to do. Use three for statements to loop through each indexer to get to each instance of Foos.
for (int x = 0; x < foos.Length; x++) {
for (int y = 0; y < foos[x].Length; y++) {
for (int z = 0; z < foos[x][y].Length; z++) {
Console.WriteLine(foos[x][y][z].Member);
}
}
}

Genetic algorithm - clustering points on screen

Below is the code I wrote for clustering using genetic algorithm. Points are from a picturebox, generated randomly (X,Y) before calling this class. However, the result of this algorithm is much worse than k-means or lbg I'm comparing it to. Can someone take a look for any errors in the algorithm, maybe I omitted something. Thanks.
I did this using arrays, the 2 other I did using lists, but I don't think that should have any impact on result.
public class geneticAlgorithm
{
static int pom = 0;
static PictureBox pb1;
public geneticAlgorithm(PictureBox pb)
{
pb1 = pb;
}
public static void doGA(PointCollection points, int clusterCounter)
//points is a list of points,
//those point have (X,Y) coordinates generated randomly from pictureBox
//coordinates. clusterCounter is how many clusters I want to divide the points into
{
//this part converts list of points into array testtab,
//where each array field hold X,Y of a point
Point[] test = new Point[points.Count];
test = points.ToArray();
double[][] testtab = new double[test.Length][];
for (int i = 0; i < testtab.GetLength(0); i++)
{
testtab[i] = new double[2];
testtab[i][0] = test[i].X;
testtab[i][1] = test[i].Y;
}
//end of converting
int n = testtab.GetLength(0);
int k = clusterCounter;
int chromosomeCount = 500;
int dimensions = 2;
double[][] testClusters = new double[k][];
for (int i = 0; i < k; i++)
{
testClusters[i] = new double[dimensions];
}
double[][] testChromosomes = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
testChromosomes[i] = new double[2 * k];
}
int[][] testChromosomesInt = new int[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
testChromosomesInt[i] = new int[2 * k];
}
double[] partner = new double[chromosomeCount];
double[][] roulette = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
roulette[i] = new double[1];
}
double[][] errors = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
errors[i] = new double[1];
}
double crossingPossibility = 0.01;
double mutationPossibility = 0.0001;
int maxIterations = 10000;
//here I create chromosomes and initial clusters
for (int j = 0; j < chromosomeCount; j++)
{
for (int i = 0; i < k; i++)
{
Random rnd = new Random();
int r = rnd.Next(n);
for (int q = 0; q < dimensions; q++)
{
testClusters[i][q] = testtab[r][q];
}
}
int help = 0;
for (int i = 0; i < k; i++)
for (int l = 0; l < dimensions; l++) // here is creation of chromosome
{
testChromosomes[j][help] = testClusters[i][l];
help++;
}
//end
//here I call accomodation function to see which of them are good
errors[j][0] = accomodationFunction(testClusters, testtab, n, k);
//end
//cleaning of the cluster table
testClusters = new double[k][];
for (int i = 0; i < k; i++)
{
testClusters[i] = new double[dimensions];
}
}
//end
for (int counter = 0; counter < maxIterations; counter++)
{
//start of the roulette
double s = 0.0;
for (int i = 0; i < chromosomeCount; i++)
s += errors[i][0];
for (int i = 0; i < chromosomeCount; i++)
errors[i][0] = chromosomeCount * errors[i][0] / s;
int idx = 0;
for (int i = 0; i < chromosomeCount; i++)
for (int j = 0; i < errors[i][0] && idx < chromosomeCount; j++)
{
roulette[idx++][0] = i;
}
double[][] newTab = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
newTab[i] = new double[2 * k];
}
Random rnd = new Random();
for (int i = 0; i < chromosomeCount; i++)
{
int q = rnd.Next(chromosomeCount);
newTab[i] = testChromosomes[(int)roulette[q][0]];
}
testChromosomes = newTab;
//end of roulette
//start of crossing chromosomes
for (int i = 0; i < chromosomeCount; i++)
partner[i] = (rnd.NextDouble() < crossingPossibility + 1) ? rnd.Next(chromosomeCount) : -1;
for (int i = 0; i < chromosomeCount; i++)
if (partner[i] != -1)
testChromosomes[i] = crossing(testChromosomes[i], testChromosomes[(int)partner[i]], rnd.Next(2 * k), k);
//end of crossing
//converting double to int
for (int i = 0; i < chromosomeCount; i++)
for (int j = 0; j < 2 * k; j++)
testChromosomes[i][j] = (int)Math.Round(testChromosomes[i][j]);
//end of conversion
//start of mutation
for (int i = 0; i < chromosomeCount; i++)
if (rnd.NextDouble() < mutationPossibility + 1)
testChromosomesInt[i] = mutation(testChromosomesInt[i], rnd.Next(k * 2), rnd.Next(10));
//end of mutation
}
//painting of the found centre on the picture box
int centrum = max(errors, chromosomeCount);
Graphics g = pb1.CreateGraphics();
SolidBrush brush = new SolidBrush(Color.Red);
for (int i = 0; i < 2 * k - 1; i += 2)
{
g.FillRectangle(brush, testChromosomesInt[centrum][i], testChromosomesInt[centrum][i + 1], 20, 20);
}
return;
}
//end of painting
public static int max(double[][] tab, int chromosomeCount)
{
double max = 0;
int k = 0;
for (int i = 0; i < chromosomeCount; i++)
{
if (max < tab[i][0])
{
max = tab[i][0];
k = i;
}
}
return k;
}
public static int[] mutation(int[] tab, int elem, int bit)
{
int mask = 1;
mask <<= bit;
tab[elem] = tab[elem] ^ mask;
return tab;
}
public static double[] crossing(double[] tab, double[] tab2, int p, int k)
{
double[] hold = new double[2 * k];
for (int i = 0; i < p; i++)
hold[i] = tab[i];
for (int i = p; i < 2 * k; i++)
hold[i] = tab2[i];
return hold;
}
//accomodation function, checks to which centre which point belongs based on distance
private static double accomodationFunction(double[][] klastry, double[][] testtab, int n, int k)
{
double Error = 0;
for (int i = 0; i < n; i++)
{
double min = 0;
int ktory = 0;
for (int j = 0; j < k; j++)
{
double dist = distance(klastry[j], testtab[i]);
if (j == 0)
{
min = dist;
}
if (min > dist)
{
min = dist;
ktory = j;
}
}
Error += min;
}
pom++;
return 1 / Error;
}
public static double distance(double[] tab, double[] tab2)
{
double dist = 0.0;
for (int i = 0; i < tab.GetLength(0); i++)
dist += Math.Pow(tab[i] - tab2[i], 2);
return dist;
}
}
The algorithm should work like so: (excuse me if not the best english)
1. Get random points (let's say 100)
2. Check into how many clusters we want to split them (the same thing I would do using k-means for example
3. Get starting population of chromosomes
4. Throu cutting on the roulette, crossing and mutation pick the best x centres, where x is the amount of clusters we want
5. Paint them.
Here are some results, and why I think it's wrong: (it's using 100 points, 5 clusters)
k-means:
lbg:
genetic(without colors now):
I hope this clarifies a bit.

c# adding random numbers to array

I am making a array filled with random numbers in c# but I can't get it to work.
int[,] array = new int[10, 5];
int x, y;
x = 0;
y = 0;
while (y <= 5)
{
Random r = new Random();
int rand = r.Next(-50, 50);
array[x, y] = rand;
if (x == 10)
{
x = 0;
y++;
}
x++;
}
Use nested for loops, it is much easier:
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5; j++)
{
array[i, j] = rnd.Next(-50, 50);
}
}
Your while loop is not readable but it's correct,except you should change while (y <= 5) to while (y < 5) otherwise you will get an IndexOutOfRangeException. And you should define your Random instance outside of the loop.
int[,] array = new int[10, 5];
int x = 0, y = 0;
Random r = new Random();
while (y < 5)
{
int rand = r.Next(-50, 50);
array [x, y] = rand;
x++;
if (x == 10)
{
x = 0;
y++;
}
}
Try this:
int[,] array = new int[10, 5];
Random rnd = new Random();
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 5; col++)
{
array[row, col] = rnd.Next(-50, 50);
}
}
you need to change yours if or array declaration to
int[,] array = new int[11, 6];
also there is other problem, you need to create random before while
Random r = new Random();
while (y <= 5)
{
to print out the values you can use for
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
Console.WriteLine(array[i, j]);
}
int[,] array = new int[10, 5];
int x, y;
x = 0;
y = 0;
while (y < 5)
{
Random r = new Random();
int rand = r.Next(-50, 50);
array[x, y] = rand;
if (x == 9)
{
x = 0;
y++;
}
x++;
}
Let's see if this works.

Categories

Resources