After changing tabpage, the combobox crashes - c#

I have a combobox outside my tabcontrol. In each tab control there is a datagridview full of values. In the combobox you can choose a conversion for all values. For example eV→meV.
When i am in the first tab and use the combobox there are no problems, but after i switch the tab and then wanna use the combobox the program list down however the whole combobox is full of try/catch
private void OpenB_Click(object sender, EventArgs e)
{
string[] result = new string[2];
bool lesen = false;
int Spalte = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Datagridview will be rested, so all values and rows are removed
for (int i = 1; i < Anzahl; i++)
{
DGV[i].Rows.Clear();
}
Anzahl = openFileDialog1.FileNames.Length;
counter = new int[Anzahl];
try
{
if (tabControl1.TabCount < Anzahl)
{
for (int i = 1; i <= Anzahl; i++)
{
if (i > tabControl1.TabCount)
{
string title = "Tab " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
DataGridView NewDGV = new DataGridView();
NewDGV.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
NewDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NewDGV.Columns.Add("Energy", "Energy");
NewDGV.Columns[0].ReadOnly = true;
NewDGV.Columns.Add("Count Rate", "Count Rate");
NewDGV.Columns[1].ReadOnly = true;
NewDGV.Location = new System.Drawing.Point(3, 3);
NewDGV.Name = "NewDGV" + Convert.ToString(i);
NewDGV.RowHeadersVisible = false;
NewDGV.Size = new System.Drawing.Size(276, 379);
NewDGV.TabIndex = i;
foreach (DataGridViewColumn col in NewDGV.Columns)
col.SortMode = DataGridViewColumnSortMode.NotSortable;
NewDGV.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DGV.Add(NewDGV);
tabControl1.TabPages[i - 1].Controls.Add(NewDGV);
}
}
}
else if (tabControl1.TabCount > Anzahl)
{
for (int i = tabControl1.TabCount - 1; i >= Anzahl; i--)
{
tabControl1.TabPages.Remove(tabControl1.TabPages[i]);
}
}
}
catch { }
try
{
//Double arrays and Datagridview will be attuned to the count of data
eV = new double[openFileDialog1.FileNames.Length][];
meV = new double[openFileDialog1.FileNames.Length][];
cm = new double[openFileDialog1.FileNames.Length][];
CR = new double[openFileDialog1.FileNames.Length][];
CRmax = new double[openFileDialog1.FileNames.Length][];
for (int i = 0; i < Anzahl; i++)
{
//Naming the columns after data names
string[] Dateiname = openFileDialog1.FileNames[i].Split('\\');
int L = Dateiname.Length;
tabControl1.TabPages[i].Text = Dateiname[L-1];
}
}
catch
{
}
//Datafiles will be read one by one
DataRead(result, ref lesen, ref Spalte);
}
}
/// Reading loop
///
/// double[] eV2 = Energy values of the current data file in eV
/// double[] meV2 = Energy values of the current data file in meV
/// double[] cm2 = Energy values of the current data file in cm^-1
/// double[] CR2 = Intensities of the current data file in CR
/// double[] CRmax2 = normalizied Intensities of the current data file in 1/CRmax
private void DataRead(string[] result, ref bool lesen, ref int Spalte)
{
for (Spalte = 0; Spalte < Anzahl; Spalte++)
{
string line;
lesen = false;
counter[Spalte] = 0;
try
{
Ursprung = openFileDialog1.FileNames[Spalte];
//initialize stream reader
System.IO.StreamReader file1 = new System.IO.StreamReader(openFileDialog1.FileNames[Spalte]);
//read line per line in stream reader
while (((line = file1.ReadLine()) != null))
{
counter[Spalte]++;
Count2 = counter[Spalte];
Count2 = Count2 / 2;
try
{
string[] splitter = line.Split(' ');
if ((splitter[0] == "S") && (splitter[1] == "0000"))
{
lesen = true;
counter[Spalte] = 0;
}
if (lesen == true)
{
//Rows will be filled an added with data value strings
if (counter[Spalte] % 2 == 0)
{
result[0] = splitter[2];
}
else
{
result[1] = splitter[2];
dataGridView1.Rows.Add();
DGV[Spalte].Rows.Add();
int Zeile = (counter[Spalte] - 1) / 2;
DGV[Spalte][0, Zeile].Value = result[0];
DGV[Spalte][1, Zeile].Value = result[1];
}
}
}
catch
{
continue;
}
}
//Streamreader is closed
file1.Close();
counter[Spalte] = counter[Spalte] / 2;
//Current datagridviw values are saved in arrays
//The conversions will be calculated and saved in new arrays
//So every unit gets its own array
double[] eV2 = new double[counter[Spalte]];
double[] meV2 = new double[counter[Spalte]];
double[] cm2 = new double[counter[Spalte]];
double[] CR2 = new double[counter[Spalte]];
double[] CRmax2 = new double[counter[Spalte]];
//Conversion calculation
for (int i = 0; i < counter[Spalte]; i++)
{
eV2[i] = Convert.ToDouble(DGV[Spalte][0, i].Value);
CR2[i] = Convert.ToDouble(DGV[Spalte][1, i].Value);
meV2[i] = 1000 * eV2[i];
cm2[i] = 8066 * eV2[i];
}
//Current file's arrays are saved in double arrays
eV[Spalte] = eV2;
CR[Spalte] = CR2;
meV[Spalte] = meV2;
cm[Spalte] = cm2;
for (int i = 0; i < counter[Spalte]; i++)
{
CRmax2[i] = CR2[i] / CR2.Max();
}
CRmax[Spalte] = CRmax2;
//Chosen conversion replaces values in datagridview
if (Hilfe == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV2[i];
}
}
else if (Hilfe == 2)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm2[i];
}
}
if (Hilfe2 == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][1, i].Value = CRmax2[i];
}
}
}
catch
{
MessageBox.Show("Es ist ein Fehler beim Einlesen eingetreten");
}
}
}
/// Energy Unit
/// Choses between eV, meV, 1/cm
/// Datagridview values are replaced by the unit array values
/// Hilfe... Saves current energy unit
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int L = comboBox1.SelectedIndex;
try
{
if (L == 0)
{
Hilfe = 1;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
}
}
catch
{
}
}
if (L == 1)
{
Hilfe = 2;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm[Spalte][i];
}
}
}
catch
{
}
}
if (L == 2)
{
Hilfe = 0;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = eV[Spalte][i];
}
}
}
catch
{
}
}
}
catch { }
}

Accept these answer if you dont know how to post your own answer?.
Answer:
Problem fixed. The reason was the dgv.autosizemode , when i deactivate it before the conversions it runs.
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}

Related

trouble with displaying ships names when they are sunk

the problem i'm facing right now is that i don't know how to check on the opponent's move which ships it sinks so i can display a message saying "Your ____ has sunk".
this is the code i have written
namespace Naval
{
public partial class Form2 : Form
{
const int Size_grid = 10;
const int picturebox = 50;
PictureBox[,] playerBoard = new PictureBox[Size_grid, Size_grid];
PictureBox[,] opponentBoard = new PictureBox[Size_grid, Size_grid];
int[,] playerShips = new int[Size_grid, Size_grid];
int[,] opponentShips = new int[Size_grid, Size_grid];
int[] Lengths = new int[] { 5, 4, 3, 2 };
//string[] Names = new string[] { "Αεροπλανοφόρο", "Αντιτορπιλικό", "Πολεμικό", "Υποβρύχιο" };
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox playerPictureBox = new PictureBox();
playerPictureBox.Size = new Size(picturebox, picturebox);
playerPictureBox.Location = new Point(col * (picturebox + 10) + 185, row * (picturebox + 10) + 245);
playerPictureBox.Click += PictureBox_Click;
playerPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
playerPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(playerPictureBox);
playerBoard[row, col] = playerPictureBox;
}
}
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox opponentPictureBox = new PictureBox();
opponentPictureBox.Size = new Size(picturebox, picturebox);
opponentPictureBox.Location = new Point(col * (picturebox + 10) + 1145, row * (picturebox + 10) + 245);
opponentPictureBox.Click += PictureBox_Click;
opponentPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
opponentPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(opponentPictureBox);
opponentBoard[row, col] = opponentPictureBox;
}
}
PlacePlayerShips(playerShips, Lengths);
PlaceOpponentShips(opponentShips, Lengths);
}
private void PictureBox_Click(object sender, EventArgs e)
{
PictureBox pictureBox = (PictureBox)sender;
int row = (pictureBox.Location.Y - 245) / (picturebox + 10);
int col = (pictureBox.Location.X - 1145) / (picturebox + 10);
if (pictureBox.Location.X >= 1145 && pictureBox.ImageLocation == null) // opponent board
{
if (row >= 0 && row < opponentShips.GetLength(0) && col >= 0 && col < opponentShips.GetLength(1))
{
if (opponentShips[row, col] > 0)
{
pictureBox.ImageLocation = "x.png";
}
else
{
pictureBox.ImageLocation = "-.png";
}
ComputerMove();
}
}
}
private void ComputerMove()
{
Random random = new Random();
int row = random.Next(Size_grid);
int col = random.Next(Size_grid);
while (playerBoard[row, col].ImageLocation != null)
{
row = random.Next(Size_grid);
col = random.Next(Size_grid);
}
if (playerShips[row, col] > 0)
{
playerBoard[row, col].ImageLocation = "x.png";
}
else
{
playerBoard[row, col].ImageLocation = "-.png";
}
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void PlacePlayerShips(int[,] playerShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row, col + i] = 1;
playerBoard[row, col + i].BackColor = Color.LightBlue;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row + i, col] = 1;
playerBoard[row + i, col].BackColor = Color.LightBlue;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void PlaceOpponentShips(int[,] opponentShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
;
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row, col + i] = 1;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row + i, col] = 1;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
int time = 0;
private void timer1_Tick(object sender, EventArgs e)
{
time++;
label42.Text= time.ToString();
}
private void timer2_Tick(object sender, EventArgs e)
{
label44.Text = " ";
timer2.Enabled = false;
}
}
}
i tried adding a switch with choices 1-4 but it didn't work i've also tried having a int[] ship Hits = new int[] {0,0,0,0} and just adding 1 every time a ship was hit but that didn't go as planned because i didn't know how to bind each item of the array to a ship . and i think that's about it
One approach that you might find helpful would be to bundle up all the information about a Ship into a class. This is an abstraction that could make it easier for displaying ship names when they are sunk. At the same time, use inheritance so that a Ship is still a PictureBox with all the functionality that implies.
Ship minimal class example
Member properties tell us what we need know about a ship. Use enum values to make the intent perfectly clear.
class Ship : PictureBox
{
#region P R O P E R T I E S
[Description("Type")]
public τύπος τύπος
{
get => _τύπος;
set
{
if (!Equals(_τύπος, value))
{
_τύπος = value;
switch (_τύπος)
{
case τύπος.Αεροπλανοφόρο: Image = Image.FromFile(Path.Combine(_imageDir, "aircraft-carrier.png")); break;
case τύπος.Αντιτορπιλικό: Image = Image.FromFile(Path.Combine(_imageDir, "destroyer.png")); break;
case τύπος.Πολεμικό: Image = Image.FromFile(Path.Combine(_imageDir, "military.png")); break;
case τύπος.Υποβρύχιο: Image = Image.FromFile(Path.Combine(_imageDir, "submarine.png")); break;
}
}
}
}
τύπος _τύπος = 0;
public bool Sunk { get; set; }
[Description("Flag")]
public σημαία σημαία
{
get => _σημαία;
set
{
_σημαία = value;
onUpdateColor();
}
}
σημαία _σημαία = σημαία.Player;
#endregion P R O P E R T I E S
private void onUpdateColor()
{
var color =
Sunk ? Color.Red :
σημαία.Equals(σημαία.Player) ?
Color.Navy :
Color.DarkOliveGreen;
for (int x = 0; x < Image.Width; x++) for (int y = 0; y < Image.Height; y++)
{
Bitmap bitmap = (Bitmap)Image;
if (bitmap.GetPixel(x, y).R < 0x80)
{
bitmap.SetPixel(x, y, color);
}
}
Refresh();
}
public Point[] Hits { get; set; } = new Point[0];
public override string ToString() =>
$"{σημαία} {τύπος} # {((TableLayoutPanel)Parent)?.GetCellPosition(this)}";
private readonly static string _imageDir =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
}
Where enum values are:
enum Direction
{
Horizontal,
Vertical,
}
enum τύπος
{
[Description("Aircraft Carrier")]
Αεροπλανοφόρο = 5,
[Description("Destroyer")]
Αντιτορπιλικό = 4,
[Description("Military")]
Πολεμικό = 3,
[Description("Submarine")]
Υποβρύχιο = 2,
}
/// <summary>
/// Flag
/// </summary>
enum σημαία
{
Player,
Opponent,
}
Displaying ships names when they are sunk
When the inherited Ship version of PictureBox is clicked the information is now available.
private void onAnyShipClick(object sender, EventArgs e)
{
if (sender is Ship ship)
{
MessageBox.Show(ship.ToString());
}
}
Images credit: Robuart
Used under license.

My code is showing compiler erros and I dont know why even though the code seems correct

Ok so I finished my code n queens genetics in c# but I keep getting these compiler errors even though I changed the code several times
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NQueen1
{
class Program
{
private const int sSize = 75; // Population size at start.
private const int mTest = 1000; // Arbitrary number of test cycles.
private const double pMating = 0.7; // Probability of two chromosomes mating. Range: 0.0 < MATING_PROBABILITY < 1.0
private const double rMutation = 0.001; // Mutation Rate. Range: 0.0 < MUTATION_RATE < 1.0
private const int minS = 10; // Minimum parents allowed for selection.
private const int MaxS = 50; // Maximum parents allowed for selection. Range: MIN_SELECT < MAX_SELECT < START_SIZE
private const int offSpring = 20; // New offspring created per generation. Range: 0 < OFFSPRING_PER_GENERATION < MAX_SELECT.
private const int minRandom = 8; // For randomizing starting chromosomes
private const int maxShuffles = 20;
private const int maxPBC = 4; // Maximum Position-Based Crossover points. Range: 0 < PBC_MAX < 8 (> 8 isn't good).
private const int maxLength = 10; // chess board width.
private static int epoch = 0;
private static int childCount = 0;
private static int nextMutation = 0; // For scheduling mutations.
private static int mutations = 0;
private static List<Chromosome> population = new List<Chromosome>();
private static void algorithm()
{
int popSize = 0;
Chromosome thisChromo = null;
bool done = false;
initializeChromosomes();
mutations = 0;
nextMutation = getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
while (!done)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if ((thisChromo.conflicts() == 0) || epoch == mTest)
{
done = true;
}
}
getFitness();
rouletteSelection();
mating();
prepNextEpoch();
epoch++;
// This is here simply to show the runtime status.
Console.WriteLine("Epoch: " + epoch);
}
Console.WriteLine("done.");
if (epoch != rMutation)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if (thisChromo.conflicts() == 0)
{
printSolution(thisChromo);
}
}
}
Console.WriteLine("Completed " + epoch + " epochs.");
Console.WriteLine("Encountered " + mutations + " mutations in " + childCount + " offspring.");
return;
}
private static void getFitness()
{
// Lowest errors = 100%, Highest errors = 0%
int popSize = population.Count;
Chromosome thisChromo = null;
double bestScore = 0;
double worstScore = 0;
// The worst score would be the one with the highest energy, best would be lowest.
worstScore = population[maximum()].conflicts();
// Convert to a weighted percentage.
bestScore = worstScore - population[minimum()].conflicts();
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.fitness((worstScore - thisChromo.conflicts()) * 100.0 / bestScore);
}
return;
}
private static void rouletteSelection()
{
int j = 0;
int popSize = population.Count;
double genT = 0.0;
double selT = 0.0;
int maximumToSelect = getRandomNumber(minS, MaxS);
double rouletteSpin = 0.0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
bool done = false;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
genT += thisChromo.fitness();
}
genT *= 0.01;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selectionProbability(thisChromo.fitness() / genT);
}
for (int i = 0; i < maximumToSelect; i++)
{
rouletteSpin = getRandomNumber(0, 99);
j = 0;
selT = 0;
done = false;
while (!done)
{
thisChromo = population[j];
selT += thisChromo.selectionProbability();
if (selT >= rouletteSpin)
{
if (j == 0)
{
thatChromo = population[j];
}
else if (j >= popSize - 1)
{
thatChromo = population[popSize - 1];
}
else
{
thatChromo = population[j - 1];
}
thatChromo.selected(true);
done = true;
}
else
{
j++;
}
}
}
return;
}
// This is where you can choose between options:
// To choose between crossover options, uncomment one of:
// partiallyMappedCrossover(),
// positionBasedCrossover(), while keeping the other two commented out.
private static void mating()
{
int getRand = 0;
int parentA = 0;
int parentB = 0;
int newIndex1 = 0;
int newIndex2 = 0;
Chromosome newChromo1 = null;
Chromosome newChromo2 = null;
for (int i = 0; i < offSpring; i++)
{
parentA = chooseParent();
// Test probability of mating.
getRand = getRandomNumber(0, 100);
if (getRand <= pMating * 100)
{
parentB = chooseParent(parentA);
newChromo1 = new Chromosome();
newChromo2 = new Chromosome();
population.Add(newChromo1);
newIndex1 = population.IndexOf(newChromo1);
population.Add(newChromo2);
newIndex2 = population.IndexOf(newChromo2);
// Choose either, or both of these:
partialCrossover(parentA, parentB, newIndex1, newIndex2);
//positionBasedCrossover(parentA, parentB, newIndex1, newIndex2);
if (childCount - 1 == nextMutation)
{
exchangeMutation(newIndex1, 1);
}
else if (childCount == nextMutation)
{
exchangeMutation(newIndex2, 1);
}
population[newIndex1].computeConflicts();
population[newIndex2].computeConflicts();
childCount += 2;
// Schedule next mutation.
if (childCount % (int)Math.Round(1.0 / rMutation) == 0)
{
nextMutation = childCount + getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
}
}
} // i
return;
}
private static void partialCrossover(int chromA, int chromB, int child1, int child2)
{
int j = 0;
int item1 = 0;
int item2 = 0;
int pos1 = 0;
int pos2 = 0;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
int crossPoint1 = getRandomNumber(0, maxLength - 1);
int crossPoint2 = getExclusiveRandomNumber(maxLength - 1, crossPoint1);
if (crossPoint2 < crossPoint1)
{
j = crossPoint1;
crossPoint1 = crossPoint2;
crossPoint2 = j;
}
// Copy Parent genes to offspring.
for (int i = 0; i < maxLength; i++)
{
newChromo1.data(i, thisChromo.data(i));
newChromo2.data(i, thatChromo.data(i));
}
for (int i = crossPoint1; i <= crossPoint2; i++)
{
// Get the two items to swap.
item1 = thisChromo.data(i);
item2 = thatChromo.data(i);
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo1.data(j) == item1)
{
pos1 = j;
}
else if (newChromo1.data(j) == item2)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo1.data(pos1, item2);
newChromo1.data(pos2, item1);
}
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo2.data(j) == item2)
{
pos1 = j;
}
else if (newChromo2.data(j) == item1)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo2.data(pos1, item1);
newChromo2.data(pos2, item2);
}
} // i
return;
}
private static void positionCrossover(int chromA, int chromB, int child1, int child2)
{
int k = 0;
int numPoints = 0;
int[] tempArray1 = new int[maxLength];
int[] tempArray2 = new int[maxLength];
bool matchFound = false;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
// Choose and sort the crosspoints.
numPoints = getRandomNumber(0, maxPBC);
int[] crossPoints = new int[numPoints];
int negativeNancy = -1;
for (int i = 0; i < numPoints; i++)
{
crossPoints[i] = getRandomNumber(0, maxLength - negativeNancy, crossPoints);
} // i
// Get non-chosens from parent 2
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thatChromo.data(i) == thisChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray1[k] = thatChromo.data(i);
k++;
}
} // i
// Insert chosens into child 1.
for (int i = 0; i < numPoints; i++)
{
newChromo1.data(crossPoints[i], thisChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 1.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo1.data(i, tempArray1[k]);
k++;
}
} // i
// Get non-chosens from parent 1
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thisChromo.data(i) == thatChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray2[k] = thisChromo.data(i);
k++;
}
} // i
// Insert chosens into child 2.
for (int i = 0; i < numPoints; i++)
{
newChromo2.data(crossPoints[i], thatChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 2.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo2.data(i, tempArray2[k]);
k++;
}
} // i
return;
}
private static void exchangeMutation(int index, int exchanges)
{
int i = 0;
int tempData = 0;
Chromosome thisChromo = null;
int gene1 = 0;
int gene2 = 0;
bool done = false;
thisChromo = population[index];
while (!done)
{
gene1 = getRandomNumber(0, maxLength - 1);
gene2 = getExclusiveRandomNumber(maxLength - 1, gene1);
// Exchange the chosen genes.
tempData = thisChromo.data(gene1);
thisChromo.data(gene1, thisChromo.data(gene2));
thisChromo.data(gene2, tempData);
if (i == exchanges)
{
done = true;
}
i++;
}
mutations++;
return;
}
private static int chooseParent()
{
// Overloaded function, see also "chooseparent(ByVal parentA As Integer)".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
return parent;
}
{
// Overloaded function, see also "chooseparent()".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
if (parent != parentA)
{
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
}
return parent;
}
private static void prepNextEpoch()
{
int popSize = 0;
Chromosome thisChromo = null;
// Reset flags for selected individuals.
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selected(false);
}
return;
}
private static void printSolution(Chromosome bestSolution)
{
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
// Clear the board.
for (int x = 0; x < maxLength; x++)
{
for (int y = 0; y < maxLength; y++)
{
board[x][y] = "";
}
}
for (int x = 0; x < maxLength; x++)
{
board[x][bestSolution.data(x)] = "Q";
}
// Display the board.
Console.WriteLine("Board:");
for (int y = 0; y < maxLength; y++)
{
for (int x = 0; x < maxLength; x++)
{
if (string.ReferenceEquals(board[x][y], "Q"))
{
Console.Write("Q ");
}
else
{
Console.Write(". ");
}
}
Console.Write("\n");
}
return;
}
private static int getRandomNumber(int low, int high)
{
return (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
}
private static int getExclusiveRandomNumber(int high, int except)
{
bool done = false;
int getRand = 0;
while (!done)
{
getRand = (new Random()).Next(high);
if (getRand != except)
{
done = true;
}
}
return getRand;
}
private static int getRandomNumber(int low, int high, int[] except)
{
bool done = false;
int getRand = 0;
if (high != low)
{
while (!done)
{
done = true;
getRand = (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
for (int i = 0; i < except.Length; i++) //UBound(except)
{
if (getRand == except[i])
{
done = false;
}
} // i
}
return getRand;
}
else
{
return high; // or low (it doesn't matter).
}
}
private static int minimum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() < thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static int maximum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() > thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static void initializeChromosomes()
{
int shuffles = 0;
Chromosome newChromo = null;
int chromoIndex = 0;
for (int i = 0; i < sSize; i++)
{
newChromo = new Chromosome();
population.Add(newChromo);
chromoIndex = population.IndexOf(newChromo);
// Randomly choose the number of shuffles to perform.
shuffles = getRandomNumber(minRandom, maxShuffles);
exchangeMutation(chromoIndex, shuffles);
population[chromoIndex].computeConflicts();
}
return;
}
private class Chromosome
{
internal int[] mData = new int[maxLength];
internal double mFitness = 0.0;
internal bool mSelected = false;
internal double mSelectionProbability = 0.0;
internal int mConflicts = 0;
public Chromosome()
{
for (int i = 0; i < maxLength; i++)
{
this.mData[i] = i;
}
return;
}
public virtual void computeConflicts()
{
int x = 0;
int y = 0;
int tempx = 0;
int tempy = 0;
//string[][] board = new string[MAX_LENGTH][MAX_LENGTH];
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
int conflicts = 0;
int[] dx = new int[] { -1, 1, -1, 1 };
int[] dy = new int[] { -1, 1, 1, -1 };
bool done = false;
// Clear the board.
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < maxLength; j++)
{
board[i][j] = "";
}
}
for (int i = 0; i < maxLength; i++)
{
board[i][this.mData[i]] = "Q";
}
// Walk through each of the Queens and compute the number of conflicts.
for (int i = 0; i < maxLength; i++)
{
x = i;
y = this.mData[i];
// Check diagonals.
for (int j = 0; j <= 3; j++)
{
tempx = x;
tempy = y;
done = false;
while (!done)
{
tempx += dx[j];
tempy += dy[j];
if ((tempx < 0 || tempx >= maxLength) || (tempy < 0 || tempy >= maxLength))
{
done = true;
}
else
{
if (board[tempx][tempy].ToString().ToUpper().Equals("Q"))// ignore the case of 2 strings
{
conflicts++;
}
}
}
}
}
this.mConflicts = conflicts;
}
public virtual void conflicts(int value)
{
this.mConflicts = value;
return;
}
public virtual int conflicts()
{
return this.mConflicts;
}
public virtual double selectionProbability()
{
return mSelectionProbability;
}
public virtual void selectionProbability(double SelProb)
{
mSelectionProbability = SelProb;
return;
}
public virtual bool selected()
{
return mSelected;
}
public virtual void selected(bool sValue)
{
mSelected = sValue;
return;
}
public virtual double fitness()
{
return mFitness;
}
public virtual void fitness(double score)
{
mFitness = score;
return;
}
public virtual int data(int index)
{
return mData[index];
}
public virtual void data(int index, int value)
{
mData[index] = value;
return;
}
} // Chromosome
static void Main(string[] args)
{
algorithm();
return;
}
}
}
This is the second code here:
namespace NQueen1
{
internal static class RectangularArrays
{
internal static string[][] ReturnRectangularStringArray(int size1, int size2)
{
string[][] newArray = new string[size1][];
for (int array1 = 0; array1 < size1; array1++)
{
newArray[array1] = new string[size2];
}
return newArray;
}
}
}
THe Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at NQueen1.Program.rouletteSelection() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 143
at NQueen1.Program.algorithm() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 56
at NQueen1.Program.Main(String[] args) in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 841
I have no clue why its throwing off these errors I tried about almost everything I could think of to fix it
This is just a random guess.
My Spidey Senses tells me thisChromo = population[j] is probably overrunning the size of array, i.e. its in a while loop with j++ and there is no real bounds checking
private static void rouletteSelection()
{
...
for (int i = 0; i < maximumToSelect; i++)
{
...
while (!done)
{
thisChromo = population[j];
...
j++;
If this is the problem, I'd consider the possibility that j will be larger than population.Length and therefore breaking out of the loop; using an if statement; or just refactoring this logic
Tips for your future questions
If you have a runtime error, show us the line of code it has the error on
Pasting code is vital, however pasting too much is annoying and hard to read
If you paste code, at least try to format it
Learn to use the debugger and breakpoints (see: How to use the Debugger, Using Breakpoints).

Calculate datagridview Cell Sepratly based on data c#

Datagridview calculate Amount each cell Differently based on data from database if addition then addition should be done if subtraction then subtraction to be done.
i have created this method but it affects all cell with answer. only the above cell should be calculated.
public void datagridviewone()
{
int addvalue = 0, subractvalue = 0;
ds = cs.Select("select ChargesProperty from FrieghtGridview");
list.Clear();
addition.Clear();
subtraction.Clear();
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
if(ds.Tables[0].Rows[j][0].ToString() == "Answer")
{
list.Add(j);
}
if(ds.Tables[0].Rows[j][0].ToString() == "Plus")
{
addition.Add(j);
}
if(ds.Tables[0].Rows[j][0].ToString() == "Minus")
{
subtraction.Add(j);
}
}
if (list.Count > 0)
{
for(int j = 0; j < list.Count; j++)
{
if(addition.Count > 0)
{
for(int adval = 0; adval <= addition.Count-1; adval++)
{
if
(dataGridView1.Rows[addition[adval]].Cells[3].Value.ToString()
!= "")
{
addvalue +=
Convert.ToInt32(dataGridView1.Rows[addition[adval]].Cells[3].Value);
}
}
}
if (subtraction.Count > 0)
{
for (int adval = 0; adval <= subtraction.Count - 1;
adval++)
{
if
(dataGridView1.Rows[subtraction[adval]].Cells[3].Value.ToString() != "")
{
subractvalue +=
Convert.ToInt32(dataGridView1.Rows[subtraction[adval]].Cells[3].Value);
}
}
}
var finalans = addvalue - subractvalue;
dataGridView1.Rows[list[0]].Cells[3].Value = finalans;
addvalue = 0;
subractvalue = 0;
finalans = 0;
}
}
}

Copying values from dynamic textbox to jagged array error

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).

My two dimensional array does not want to accept all my data

I am giving an array a size by what is contained in the text file. So when I look at my array it shows [4,7]. But when I read data into the array it only goes up until [1,6].
Take note that the last name is a position of the data in the array, the other entries then shows a ? sign and a no-entry sign on the right.
What is wrong with the below code?
static void buildArray()
{
int rowCount = 0;
int colCount = 0;
int placeHolder = 0;
double devideNumber = 0;
int tempNumber = 0;
string typeOptimum;
string[] objValue;
string[] constraintValues;
List<string> testNumbers;
List<double> ratioList;
List<double> rhs;
foreach (string item in constraintsList)
{
if (rowCount > 0)
{
colCount++;
}
rowCount++;
}
rowCount = colCount + 1;
colCount = colCount + 4;
string[,] arrayConstraints = new string[8, 9];
//Console.WriteLine("row {0} col {1}", colCount+1, colCount+4);
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
arrayConstraints[i, j] = "0";
}
}
arrayConstraints[0, 0] = "1";
objValue = constraintsList[0].Split(' ');
typeOptimum = objValue[0].ToUpper();
arrayConstraints[0, 1] = (int.Parse(objValue[1]) * -1).ToString();
arrayConstraints[0, 2] = (int.Parse(objValue[2]) * -1).ToString();
for (int i = 1; i < rowCount; i++)
{
constraintValues = constraintsList[i].Split(' ');
arrayConstraints[i, 1] = constraintValues[0];
arrayConstraints[i, 2] = constraintValues[1];
arrayConstraints[i, i + 2] = "1";
arrayConstraints[i, colCount - 1] = constraintValues[3];
}
//for (int i = 0; i < rowCount; i++)
//{
// Console.WriteLine(" ");
// for (int j = 0; j < colCount; j++)
// {
// Console.Write(arrayConstraints[i, j] + " ");
// }
//}
do
{
//Console.WriteLine(testNumbers[entryPosition]);
//Console.WriteLine(arrayConstraints[0,entryPosition+1]);
//Console.WriteLine(entryPosition+1);
testNumbers = new List<string>();
for (int i = 1; i < colCount - 1; i++)
{
testNumbers.Add(arrayConstraints[0, i]);
}
ratioList = new List<double>();
rhs = new List<double>();
for (int i = 1; i < rowCount; i++)
{
ratioList.Add(double.Parse(arrayConstraints[i, entryPosition + 1]));
rhs.Add(double.Parse(arrayConstraints[i, colCount - 1]));
}
placeHolder = findRatioTest(ratioList, rhs);
#region multiplyArray
for (int i = 0; i < rowCount; i++)
{
if (i == placeHolder)
{
devideNumber = double.Parse(arrayConstraints[entryPosition + 1, placeHolder]);
for (int j = 0; j < colCount; j++)
{
tempNumber = int.Parse(arrayConstraints[placeHolder, j]);
arrayConstraints[placeHolder, j] = (tempNumber / devideNumber).ToString();
}
}
else
{
for (int k = 0; k < colCount; k++)
{
arrayConstraints[i, k] = (double.Parse(arrayConstraints[i, k]) - (double.Parse(arrayConstraints[i, entryPosition + 1])) * double.Parse(arrayConstraints[placeHolder, k])).ToString();
}
}
}
#endregion
foreach (string item in arrayConstraints)
{
Console.WriteLine(item);
}
} while (findNumber(typeOptimum, testNumbers) == true);
//while (findNumber(typeOptimum, testNumbers) == true)
//{
// testNumbers.Clear();
// for (int i = 1; i < colCount - 1; i++)
// {
// testNumbers.Add(arrayConstraints[0, i]);
// }
//}
}
static Boolean findNumber(string type, List<string> listNumbers)
{
Boolean found = false;
int tempInt, count = 0;
tempInt = int.Parse(listNumbers[0]);
if (type == "MIN")
{
#region MIN
foreach (string item in listNumbers)
{
count++;
if (int.Parse(item) > 0 || int.Parse(item)> tempInt)
{
entryPosition = count - 1;
tempInt = int.Parse(item);
found = true;
}
}
#endregion
}
else
{
#region MAX
foreach (string item in listNumbers)
{
count++;
if (int.Parse(item) < 0 || int.Parse(item) < tempInt)
{
entryPosition = count - 1;
tempInt = int.Parse(item);
found = true;
}
}
#endregion
}
return (found);
}
static int findRatioTest(List<double> listRatio, List<double> rhs)
{
int placeHolder = 0;
List<double> ratioTest = new List<double>();
int count = 0;
double tempSmall;
int tempPlace = 0;
foreach (double item in listRatio)
{
try
{
ratioTest.Add(rhs[count]/ item);
}
catch (Exception)
{
ratioTest.Add(double.Parse("-1"));
throw;
}
count++;
}
count = 0;
tempSmall = ratioTest[0];
foreach (double item in ratioTest)
{
if (item != 0 && item > 0)
{
if (item < tempSmall)
{
tempSmall = item;
tempPlace = count;
}
}
count++;
}
placeHolder = tempPlace + 1;
ratioTest.Clear();
return (placeHolder);
}

Categories

Resources