Limit 2D Array Size on the Console (C#) - 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;
}
}

Related

Improved Selection Sort Out of Bounds Error

I have a method that is an "Improved version of Selection Sort". However, the code is not running as " temp[x] = 0;" this line gives an out of bounds of the array error. I do not want to use an ArrayList. How would I change this line to be in bounds of the array?
public static void ImprovedSelectionSort(int[] Array)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int[] temp = new int[Array.Length];
for (int x = 1; x <= Array.Length; x++)
{
//OtherList.Add(0); -- what I want to do
temp[x] = 0;
}
int n = Array.Length;
int i = 0;
while (i < n)
{
int rear = 0;
int curMax = Array[i];
temp[rear] = i;
int j = i + 1;
while (j < n)
{
if (curMax < Array[j])
{
curMax = Array[j];
rear = -1;
}
if (curMax == Array[j])
{
rear = rear + 1;
temp[rear] = j;
}
j++;
}
int front = 0;
int p = Array[temp[front]];
while (front <= rear)
{
int temporary = p;
Array[temp[front]] = Array[i];
Array[i] = temporary;
i++;
front += 1;
}
}
for (int x = 1; x <= Array.Length; x++)
This is most likely the issue. The last index in an array is the length minus 1 (so, a 52-card deck goes from 0..51). Changing the "x <= Array.Length" component to "x < Array.Length" should fix the issue.
Change the <= to < in the for loop. This is a common mistake among novice devs, and not something you should sweat. But it's a good thing to keep in mind for the future.

Function to generate random multidimensional array

I am creating a function to generate random values for a multidimensional array and I get the error "method must have a return type" and "; expected".
Here is my code:
public static Double[,] X Generate_random()
{
Random rnd = new Random();
X = new Double[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
X[i, j] = rnd.Next(0, 10);
}
}
}
I think you meant to write your code like this
public static Double[,] Gerar_Aleatorio() {
Random rnd = new Random();
Double [,] x;
x = new Double[3, 3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
x[i, j] = rnd.Next(0, 10);
}
}
return x;
}
When you declare your return type for your method (in this case, Double[,]), you need to ensure that all paths through the method will end up returning an instance of that type. This is done using the return statement, which you would just place at the end of the method:
return X;
However, you never explicitly declare what type X is. When defining a variable, you must do: [Type] [VariableName] and additionally you can do the assignment on the same line (just as you did for Random). So your X definition should look like:
Double[,] X = new Double[3, 3];
Additionally, you have a typo (I assume) in the signature, where you have an X in the signature next to the type declaration. That should be removed, so your signature looks like:
public static Double[,] Generate_random()
Putting that all together, you have:
public static Double[,] Generate_random()
{
Random rnd = new Random();
Double[,] X = new Double[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
X[i, j] = rnd.Next(0, 10);
}
}
return X;
}

Convert object containing 2D object array into string array

I have a method which returns the following type and object:
object {object[,]}
test {object[19, 2]}
Is it possible to convert this into 2d string array, or a datatable?
Looks akward, but I haven't found another way.
int firstDimensionSize = 19;
int secondDimensionSize = 2;
object[,] objectArray = new object[firstDimensionSize, secondDimensionSize];
string[,] stringArray = new string[objectArray.Length / secondDimensionSize, secondDimensionSize];
for (int i = 0; i < objectArray.Length / secondDimensionSize; i++)
{
for (int j = 0; j < secondDimensionSize; j++)
{
stringArray[i, j] = objectArray[i, j].ToString();
}
}
In case your second dimension is always the same you could leave out the inner loop, replacing it with static code.
See also https://www.dotnetperls.com/2d
I made this extension method, but you can aswell make it a normal method if you don't need it that often.
public static class Extensions
{
public static string[,] ConvertToString2D(this object[,] arr)
{
int dim1 = arr.GetLength(0);
int dim2 = arr.GetLength(1);
string[,] strArray = new string[dim1, dim2];
for (int i = 0; i < dim1; i++)
{
for (int j = 0; j < dim2; j++)
{
strArray[i, j] = Convert.ToString(arr[i, j]);
}
}
return strArray;
}
}
and then you can call it like this:
var result = objArr.ConvertToString2D();

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.

Creating a 3x3 matrix with user input numbers C#

im trying to create a 3x3 matrix in c# language, i know how to create the matrix but i need help for user input numbers. I hope someone can help me thank you for that.
I will add a while loop and use double.TryParse to validate user's input. Usin BWHazel's code:
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
double input;
Console.Write("Enter value for ({0},{1}): ", i, j);
while (!double.TryParse(Console.ReadLine(), out input)
{
Console.Write("Enter correct value for ({0},{1}): ", i, j);
}
matrix[i,j] = input
}
}
To get the totals for all rows you can use following snippet:
for (int i = 0; i < MATRIX_ROWS; i++)
{
// The some for each row
double sum = 0.0;
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
sum += matrix[i,j];
}
Console.WriteLine(string.format("The sum for row {0} is: {1}", i, sum));
}
If you are using the command-line, something like this should work:
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
Console.Write("Enter value for ({0},{1}): ", i, j);
matrix[i,j] = double.Parse(Console.ReadLine());
}
}
This assumes you are using double for the values. The .Parse() method is available for all .NET numeric types including int.
private void button1_Click(object sender, EventArgs e)
{
txtResult.Text=GenerateMatrix(Int32.Parse(txtRow.Text), Int32.Parse(txtColumn.Text));
}
private string GenerateMatrix(int Row,int Column)
{
string matrix = string.Empty;
string Result = string.Empty;
int nxtline=0;
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Column; j++)
{
if (nxtline==Column)
{
matrix = matrix + Environment.NewLine;
nxtline = 0;
}
matrix = matrix+"*";
nxtline = nxtline + 1;
}
}
Result = matrix;
return Result;
}

Categories

Resources