I am trying to make a counter using an array that I used when I created several images, after a certain amount of time the image should disappear if it is not clicked, I am new to C#, and I am very confused. I think I have it for the most part, but it does not seem to work, thanks. In the code I include the two methods that use this array, CreateImage() which creates the "Mole" image, then adds it to a random spot on the grid, and deleteMole() where I am trying to delete this mole after 4 seconds.
Code:
private void ChangeImage()
{
string Moleimage = TUtils.GetIniFileString(Moleini, "ImagePath", "PictureFile", Root + "mole2.png");
NumofImages = TUtils.GetIniInt(Moleini, "NumPictures", "pictures", 8);
String MoleImageFunction = TUtils.GetIniFileString(Moleini, "ImagePath", "PictureFile", Root + "mole2.png");
for (int j = 0; j > NumofImages; j++)
{
ListArray[j]++;
}
Image newImage = HoleImage();
molePopup = MoleImage();
int numCol = Convert.ToInt32(NumberOfColumns);
int ranCol = randomColumns.Next(1, numCol);
int ranRow = randomRow.Next(1, NumberofRows);
Image mole = new Image();
//for (int i = 0; i < NumofImages; i++)
//{
mole.Source = new BitmapImage(new Uri(MoleImageFunction));
mole.Name = "Mole" + ListArray;
mole.Width = ImageSize;
mole.Height = ImageHeight;
//}
Grid.SetColumn(mole, ranCol);
Grid.SetRow(mole, ranRow);
grid_Main.Children.Add(mole);
//Calling MoileLifeCounter for Mole Death
moleLifeCounter();
mole.MouseUp += new MouseButtonEventHandler((o, e) =>
{
grid_Main.Children.Remove(mole);
MolePoints++;
});
}
private void deleteMole()
{
NumofImages = TUtils.GetIniInt(Moleini, "NumPictures", "pictures", 8);
int NumberofImages;
NumberofImages = Convert.ToInt32(NumofImages);
for (int j = 0; j > NumofImages; j++)
{
ListArray[j]--;
if (ListArray[j] == 0)
{
int numCol = Convert.ToInt32(NumberOfColumns);
int ranCol = randomColumns.Next(1, numCol);
int ranRow = randomRow.Next(1, NumberofRows);
Image newImage = HoleImage();
Grid.SetColumn(HoleImage(), ranCol);
Grid.SetRow(HoleImage(), ranRow);
grid_Main.Children.Add(HoleImage());
Console.WriteLine("TIMER WORKED!");
}
else
{
break;
}
}
}
looks to me like the loop which decrements the counter is never entered
for (int j = 0; j > NumofImages; j++) // wrong!
should be
for (int j = 0; j < NumofImages; j++)
Related
I am trying to generate a maze and I faced a stack overflow error while trying to do divide and conquer kind of approach to my 2D array.I will have to post the whole code since I have no idea what causes it and i am very inexperienced in the subject.
this is the details : System.StackOverflowException
HResult=0x800703E9
Message=
this is where the exception happens
!https://imgur.com/a/iwX8pKY
https://www.robinsnyder.com/MazeStaticGif I got the idea from here.
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace labirentVize2
{
class labirentOlustur
{ public static int delik;
public static int x=0;
public static int y;
public static int N = 30;
public static int boy = 30;
int[,] uret = new int[N, N];
public Array girisCikis(int[,] uret)
{
int en1=1;
Random giris = new Random();
int gir = giris.Next(1, 29);
if (gir > 14)
{
int gir2 = giris.Next(15, 28);
int gir3 = (gir + gir2)/2;
uret[0, gir] = 1;
uret[0, gir2] = 1;
uret[0, gir3] = 1;
}
else
{
int gir2 = giris.Next(1, 15);
int gir3 = (gir + gir2)/2;
uret[0, gir] = 1;
uret[0, gir2] = 1;
uret[0, gir3] = 1;
}
Random cikis = new Random();
int cik = cikis.Next(1, 28);
if (cik > 14)
{
int cik2 = cikis.Next(1, 28);
int cik3 = (cik + cik2)/2;
uret[29, cik] = 1;
uret[29, cik2] = 1;
uret[29, cik3] = 1;
}
else
{
int cik2 = cikis.Next(15, 28);
int cik3 = (cik + cik2)/2;
uret[29, cik] = 1;
uret[29, cik2] = 1;
uret[29, cik3] = 1;
}
labYap(uret, en1, x, boy);
return uret;
}
void labGoster(int[,] uret)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
Console.Write(" " + uret[i, j] + " ");
Console.WriteLine();
}
}
public void labYap(int[,] uret, int en1, int x, int boy)
{
int total1 = 0;
Random rand2 = new Random();
for (int i = 0; i < uret.GetLength(0); i++)
{
for (int j = 0; j < uret.GetLength(1); j++)
{
total1 += uret[i, j];}
}
if(total1 > 800)
{
labGoster(uret);
}
else if (total1 == 784)
{
Random rand1 = new Random();
en1 = rand1.Next(2, 29);
x = 30;
delik = rand2.Next(1, 29);
}
else
{
Random rand = new Random();
en1 = rand.Next(1, en1);
boy = boy - en1;
delik = rand2.Next(1, en1);
}
if (diziUstToplam(uret, en1) >= diziAltToplam(uret, en1))
{
y = en1;
for (int j = 0; j < x ; j++)
{
uret[en1, j] = 0;
}
uret[en1, delik] = 1;
labYap(uret, en1, x, boy);
labYap(uret, boy, x, boy);
}
else
{ x = en1;
for (int j = 0; j < en1; j++)
{
uret[j, en1] = 0;
}
uret[delik, en1] = 1;
labYap(uret, en1, x, boy);
labYap(uret, en1, x, boy);
}
int diziUstToplam(int[,] uret, int en1)
{
int total = 0;
// Dizinin ilk boyutu için
for (int i = 0; i < en1; i++)
{
// Dizinin ikinci boyutu için
for (int j = 0; j < uret.GetLength(1); j++)
{
total += uret[i, j];
}
}
return total;
}
int diziAltToplam(int[,] uret, int en1)
{
int total = 0;
// Dizinin ilk boyutu için
for (int i = en1; i < 30; i++)
{
// Dizinin ikinci boyutu için
for (int j = 0; j < uret.GetLength(1); j++)
{
total += uret[i, j];
}
}
return total;
}
int rastgeleSayi()
{
Random rand = new Random();
int en1 = rand.Next(1, 29);
return en1;
}
}
}
}
The stack overflow error is because you call labYear() too many times from within itself. You need to ensure that you have some escape condition where the function can return.
See more here: https://learn.microsoft.com/en-us/dotnet/api/system.stackoverflowexception?view=net-6.0
How can I copy the values from dynamic textboxes to a jagged array? I tried with a for cycle but I constantly get this error message:"Object reference not set to an instance of an object." What can be the problem?(the textboxes are also made with jagged arrays) Here is the full code, you can find the problematic lines in the first lines of the button1 event handler link
for (int a = 0; a < nr; a++)
{
for (int b = 0; b < nr+ 1; b++)
{
array[a][b] =int.Parse(TB[a][b].Text);
}
}
(Here's the full code:)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
int ismeretlen = 2;
TextBox[][] TB;
string file = "3ismeretlen.dat";
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int[][] egyenletek = new int[ismeretlen][];
for (int a = 0; a < ismeretlen; a++)
{
for (int b = 0; b < ismeretlen + 1; b++)
{
egyenletek[a][b] =int.Parse(TB[a][b].Text);
}
}
int változószám = TB[0].Length;
for (int i = 0; i < változószám - 1; i++)
{
for (int j = i; j < változószám - 1; j++)
{
int[] d = new int[változószám];
for (int x = 0; x < változószám; x++)
{
if (i == j && egyenletek[j][i] == 0)
{
bool changed = false;
for (int z = egyenletek.Length - 1; z > i; z--)
{
if (egyenletek[z][i] != 0)
{
int[] temp = new int[változószám];
temp = egyenletek[z];
egyenletek[z] = egyenletek[j];
egyenletek[j] = temp;
changed = true;
}
}
if (!changed)
{
textBox1.Text += "Az egyenletrendszernek nincs megoldása!\r\n";
return;
}
}
if (egyenletek[j][i] != 0)
{
d[x] = egyenletek[j][x] / egyenletek[j][i];
}
else
{
d[x] = egyenletek[j][x];
}
}
egyenletek[j] = d;
}
for (int y = i + 1; y < egyenletek.Length; y++)
{
int[] f = new int[változószám];
for (int g = 0; g < változószám; g++)
{
if (egyenletek[y][i] != 0)
{
f[g] = egyenletek[y][g] - egyenletek[i][g];
}
else
{
f[g] = egyenletek[y][g];
}
}
egyenletek[y] = f;
}
}
double val = 0;
int k = változószám - 2;
double[] eredmény = new double[egyenletek.Length];
for (int i = egyenletek.Length - 1; i >= 0; i--)
{
val = egyenletek[i][változószám - 1];
for (int x = változószám - 2; x > k; x--)
{
val -= egyenletek[i][x] * eredmény[x];
}
eredmény[i] = val / egyenletek[i][i];
if (eredmény[i].ToString() == "NaN" || eredmény[i].ToString().Contains("Végtelen sok megoldás."))
{
textBox1.Text += "Az egyenletrendszernek nincs megoldása!\n";
return;
}
k--;
TextBox[] megoldás = new TextBox[ismeretlen];
for (int b = 0; b < ismeretlen; i++)
{
megoldás[b] = new TextBox();
megoldás[b].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
megoldás[b].Left = 536+ b * 36;
megoldás[b].Top = 36 * b + 10;
megoldás[b].Width = 35;
megoldás[b].Font = new Font(megoldás[b].Font.FontFamily, 16);
megoldás[b].BackColor = Color.Cyan;
megoldás[b].TextAlign = HorizontalAlignment.Center;
megoldás[b].Text = eredmény[ismeretlen - 1].ToString();
this.panel1.Controls.Add(megoldás[b]);
}
FileStream fs = new FileStream(file, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
for (int r = 0; r < ismeretlen; r++)
for (int t = 0; t < ismeretlen + 1; t++)
bw.Write(egyenletek[r][t]);
bw.Close();
fs.Close();
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
numericUpDown1.Maximum = 6;
numericUpDown1.Minimum = 2;
}
private void Generál_Click(object sender, EventArgs e)
{
this.panel1.Controls.Clear();
ismeretlen = (int)numericUpDown1.Value;
TB = new TextBox[ismeretlen][];
for(int i = 0; i < ismeretlen; i++)
TB[i] = new TextBox[ismeretlen + 1];
int height = 20;
int width = 40;
int curX = 10;
int curY = 10;
for(int i = 0; i < ismeretlen; i++)
{
for(int j = 0; j < ismeretlen + 1; j++)
{
TextBox txtbox = new TextBox();
txtbox = new TextBox();
txtbox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
txtbox.Left = curX;
txtbox.Top = curY;
txtbox.Width = width;
txtbox.Height = height;
txtbox.Font = new Font(txtbox.Font.FontFamily, 16);
txtbox.BackColor = Color.Azure;
txtbox.TextAlign = HorizontalAlignment.Center;
TB[i][j] = txtbox;
this.panel1.Controls.Add(TB[i][j]); // Add as a child of panel
curX += width + 15;
}
curX = 10;
curY = curY + height + 20;
}
}
private void Ment_Click(object sender, EventArgs e)
{
}
}
}
In this line of code, you only initialize the first dimension of your array:
int[][] egyenletek = new int[ismeretlen][];
But you then use it before initializing the second dimension a handful of lines later (so this dimension is null (an object not set to a reference)):
egyenletek[a][b] =int.Parse(TB[a][b].Text);
Before that line, you should initialize the 2nd dimension in some way. You did this at another part of your code, in the lines of 172-173 in your jsfiddle link.
In general, when you see this error you should evaluate what objects you are reading from and assigning to and ensure they have been initialized (ie. they are not null).
So i made a button and when you press it displays a graph of the arrays, but it goes to 0 when its finished.
private void button14_Click(object sender, EventArgs e)
{
for (int i = 0; i <= period; i++)
{
xos[i] = i+1;
yos[i] = pot[i];
listBox1.Items.Add(xos[i]);
listBox1.Items.Add("y " + yos[i]);
}
for (int i = 0; i <= period; i++)
{
x2os[i] = i + 1;
y2os[i] = pot2[i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.Series["Potražnja"].Points.DataBindXY(xos, yos);
chart1.Series["Predviđanje"].Points.DataBindXY(x2os,y2os);
}
Here is a photo of chart
Don't create the arrays before you know how long they need to be, just declare the references:
public double[] xos;
public double[] yos;
public double[] y2os;
public double[] x2os;
Then when you use them, create the actual arrays:
private void button14_Click(object sender, EventArgs e)
{
xos = new double[period + 1];
yos = new double[period + 1];
x2os = new double[period + 1];
y2os = new double[period + 1];
for (int i = 0; i <= period; i++)
{
xos[i] = i+1;
yos[i] = pot[i];
listBox1.Items.Add(xos[i]);
listBox1.Items.Add("y " + yos[i]);
}
for (int i = 0; i <= period; i++)
{
x2os[i] = i + 1;
y2os[i] = pot2[i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.Series["Potražnja"].Points.DataBindXY(xos, yos);
chart1.Series["Predviđanje"].Points.DataBindXY(x2os,y2os);
}
To make the yellow line skip the first zero values, you would need to check for those first, and then create the arrays:
var start = 0;
while (start <= period && pot2[start] == 0) {
start++;
}
x2os = new double[period - start + 1];
y2os = new double[period - start + 1];
for (int i = 0; i <= period - start; i++)
{
x2os[i] = start + i + 1;
y2os[i] = pot2[start + i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}
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.
I am currently trying to implement binary sort logic. I start by generating random numbers. Then create a copy of that array which will be then sorted out with the Binary Sort method. The problem is that the sort is not working properly. I am not sure if my comparisons are being done correctly. Any ideas why is not sorting properly?
namespace binarySort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Stopwatch sw = new Stopwatch();
Random r = new Random();
OpenFileDialog open1 = new OpenFileDialog();
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
public void RandomNumber()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
for (int i = 0; i < size; i++)
{
createArray[i] = r.Next(1, max);
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Random" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void BinarySort()
{
operations = 0;
sw.Reset();
sw.Start();
int low = 0;
int high = 0;
int temp = 0;
int mid = 0;
for (int i = 0; i < size; i++)
{
copyArray[i] = createArray[i];
}
for (int i = 1; i < size; i++)
{
high = i - 1;
temp = copyArray[i];
while (low <= high)
{
operations++;
mid = (low + high) / 2;
if (temp < copyArray[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
operations++;
for (int j = i - 1; j >= low; j--)
{
copyArray[j + 1] = copyArray[j];
}
copyArray[low] = temp;
}
for (int i = 0; i < size; i++)
{
sortArray[i] = copyArray[i];
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Binary Insertion" + Environment.NewLine + Environment.NewLine);
DisplaySorted();
}
private void buttonSortArray_Click(object sender, EventArgs e)
{
BinarySort();
}
}
}
For example:
EDIT: Sorry, your original code is OK, you just need to add this line low = 0; after high = i - 1; so it should be
for (int i = 1; i < size; i++)
{
high = i - 1;
low = 0;
temp = copyArray[i];