C# array is not displaying correctly - c#

I'm trying to create a basic weather app where you can enter readings for a city and it will display the average, lowest temperature and highest temperature.
I created a 2d array (intTemps) with 5 rows (citys) and 4 columns (4 readings). Whenever I add a temperature to the listbox, it always displays in the upper left. When I add another temperature, it displays the same temperature that was just displayed and the current temperature.
The code is based on an example my professor wrote, so I'm not sure why its not displaying right.
public partial class Form1 : Form
{
string[] strNames = { "Livonia",
"Redford" ,
"Novi" ,
"Westland",
"Northville" };
int[,] intTemps = new int[5, 4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 4; i++)
{
cobNames.Items.Add(strNames[i]);
lstNames.Items.Add(strNames[i]);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (cobNames.SelectedIndex >= 0 && cobNames.SelectedIndex <= 4)
{
if (intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] == 0)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
else
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show("Do you want to change temps?", "Temps already exist!", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
}
displayTemps();
}
else
{
MessageBox.Show("You must select a valid name!");
}
}
catch (FormatException)
{
MessageBox.Show("Temps must be integers");
}
}
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
}
for (int l = 0; l <= 4; l++)
{
strLine = " ";
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] == 0)
{
strLine += " ";
}
else
{
if (intTemps[l, c] == 120)
{
strLine += intTemps[l, c] + " ";
}
else
{
strLine += intTemps[l, c] + " ";
}
lstTemp.Items.Add(strLine);
}
}
}
}
}

I rewrite your displayTemps() procedure. This wil add to lstTemp all information you need:
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
int min_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Min();
int max_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Max();
lstTemp.Items.Add(
"Average temp for city "+ l +": " + dblAverages[l] + " " +
"Minimum " + min_temp + " " +
"Maximum " + max_temp);
}
}

Related

Multiplication and Sum in GridView ASP.Net C#

I have a datatable which is bound to GridView datasource as follows.
Overall i want to Multiply 'Quantity' column value with 'Part1 qty' column value until 'column5' cell value is repeating and so on
the result of operation should appear underneath the value as highlighted in red for understanding
My GridView data currently
I want the following output
Required Output
My GridMarkup
My GridMarkup
What I have done so far is
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax=columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult=0;
int counter = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
counter++;
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity= GridView1.Rows[i-1].Cells[1].Text;
var PreviousGLQuantity= GridView1.Rows[i-1].Cells[result].Text;
//var Quantity = dt.Rows[i].ItemArray[1];
//var GLQuantity = dt.Rows[i].ItemArray[Convert.ToInt64(result)].ToString();
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
MultiplicationResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ) + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
GridView1.Rows[i].Cells[j].Text = o.ToString();
GridView1.Rows[i].Cells[j].Text.Replace("\n", "<br/>");
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}
Thanks in advance.
We can use below Answer
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax = columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult = 0;
decimal currentCellResult = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
var defaultvalue = row.Cells[j].Text.ToString();
var defaultvalueArray = defaultvalue.Split(' ');
var originalMultiplicationResult = defaultvalueArray.Count() == 2 ? defaultvalueArray.Last() : "0";
var originalCellValue = defaultvalueArray.Count() == 2 ? defaultvalueArray.First() : row.Cells[j].Text.ToString();
if (originalCellValue == previousRow.Cells[j].Text)
{
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity = GridView1.Rows[i - 1].Cells[1].Text;
var PreviousGLQuantity = GridView1.Rows[i - 1].Cells[result].Text;
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
currentCellResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ);
MultiplicationResult = currentCellResult + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
if (row.Cells[j].RowSpan == 0)
{
//DataTable dt = (DataTable)ViewState["dt"];
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text = previousRow.Cells[j].Text.Split("");
}
else
{
//DataTable dt = (DataTable)ViewState["dt"];
var t = Convert.ToDecimal(originalMultiplicationResult) - Convert.ToDecimal(currentCellResult) + MultiplicationResult;
object o = dt.Rows[i].ItemArray[j] + " " + t.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text.Replace("\n", "<br>");
}
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}

Windows Forms freezes and don't answer

My lab is about schedule and I use modified Kron algorithm.
When the button presses the form should print information on 4 richBoxes.
Sometimes everything is OK but sometimes the form freezes and don't answer. If I open the Task Manager window I see that my app takes about 30% CPU. Maybe it's because of cycle in the button? Maybe I should do more buttons? Or what? I don't understand..
So what's the prob?
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
namespace LW3_OTPR_Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBoxZ.Text = "3";
textBoxTasks.Text = "12";
textBoxProcs.Text = "4";
textBoxFrom.Text = "10";
textBoxTo.Text = "20";
}
private void buttonGetResult_Click(object sender, EventArgs e)
{
richTextBoxMatrix.Clear();
richTextBox1.Clear();
richTextBox2.Clear();
richTextBox3.Clear();
int z = Convert.ToInt32(textBoxZ.Text);
for (int i = 0; i < z; i++)
{
richTextBox1.Text += "========= Z = " + (i+1) +" ===========";
richTextBox1.Text += Environment.NewLine;
richTextBox2.Text += "========= Z = " + (i + 1) + " ===========";
richTextBox2.Text += Environment.NewLine;
richTextBox3.Text += "========= Z = " + (i + 1) + " ===========";
richTextBox3.Text += Environment.NewLine;
Work.start1(Convert.ToInt32(textBoxTasks.Text), Convert.ToInt32(textBoxProcs.Text),
Convert.ToInt32(textBoxFrom.Text), Convert.ToInt32(textBoxTo.Text));
richTextBoxMatrix.Text += "Матрица " + (i+1);
richTextBoxMatrix.Text += Environment.NewLine;
richTextBoxMatrix.Text += Work.strWork;
var processors = new Individ(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
var procMonolit = new IndividMonolit(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
var procKritWay = new IndividKritWay(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
richTextBox1.Text += processors.print();
richTextBox2.Text += procKritWay.printKritWay();
richTextBox3.Text += procMonolit.printMonolit();
processors.proc.balance();
procKritWay.procKritWay.balanceKritWay();
procMonolit.procMonolit.balanceMonolit();
richTextBox1.Text += processors.proc.inf;
richTextBox2.Text += procKritWay.procKritWay.infKritWay;
richTextBox3.Text += procMonolit.procMonolit.infMonolit;
}
}
}
static class Work
{
public static string strWork;
static public List<List<int>> arrayTask2d { set; get; }
static public List<int> arrayTask { set; get; }
static public void start1(int countWork, int countProc, int t1, int t2)
{
strWork = string.Empty;
int temp = 0;
arrayTask = new List<int>();
arrayTask2d = new List<List<int>>();
List<int> taskRow = new List<int>();
for (int i = 0; i < countWork; i++)
{
temp = Constant.rnd.Next(t2 - t1) + t1 + 1;
arrayTask.Add(temp);
taskRow = new List<int>();
for (int j = 0; j < countProc; j++)
{
taskRow.Add(temp);
}
arrayTask2d.Add(taskRow);
}
for (int i = 0; i < countWork; i++)
{
for (int j = 0; j < countProc; j++)
{
strWork += arrayTask2d[i][j].ToString() + " ";
}
strWork += Environment.NewLine;
}
}
}
class Proc
{
public string inf;
public string infMonolit;
public string infKritWay;
private List<List<int>> procs;
public List<int> this[int i]
{
get
{
return procs[i];
}
set
{
procs[i] = value;
}
}
public int CountProc
{
get { return procs.Count; }
}
public int delta
{
get
{
return procs.Max((a) => { return a.Sum(); }) - procs.Min((a) => { return a.Sum(); });
}
}
public Proc(int countProc)
{
inf = string.Empty;
infMonolit = string.Empty;
infKritWay = string.Empty;
procs = new List<List<int>>();
for (int i = 0; i < countProc; i++)
procs.Add(new List<int>());
}
private int getIndexOfMax()
{
int result = 0;
for (int i = 0; i < procs.Count; i++)
{
if (procs[i].Sum() > procs[result].Sum())
result = i;
}
return result;
}
public int getIndexOfMin()
{
int result = 0;
for (int i = 0; i < procs.Count; i++)
{
if (procs[i].Sum() < procs[result].Sum())
result = i;
}
return result;
}
private void addInf()
{
for (int i = 0; i < procs.Count; i++)
{
inf += " Процессор " + (i + 1).ToString()+ ": ";
for (int j = 0; j < procs[i].Count; j++)
inf += procs[i][j] + " ";
inf += "|| sum = " + procs[i].Sum();
inf += Environment.NewLine;
}
inf += "Δ = " + delta + Environment.NewLine;
}
private void addInfMonolit()
{
for (int i = 0; i < procs.Count; i++)
{
infMonolit += " Процессор " + (i + 1).ToString() + ": ";
for (int j = 0; j < procs[i].Count; j++)
infMonolit += procs[i][j] + " ";
infMonolit += "|| sum = " + procs[i].Sum();
infMonolit += Environment.NewLine;
}
infMonolit += "Δ = " + delta + Environment.NewLine;
}
private void addInfKritWay()
{
for (int i = 0; i < procs.Count; i++)
{
infKritWay += " Процессор " + (i + 1).ToString() + ": ";
for (int j = 0; j < procs[i].Count; j++)
infKritWay += procs[i][j] + " ";
infKritWay += "|| sum = " + procs[i].Sum();
infKritWay += Environment.NewLine;
}
infKritWay += "Δ = " + delta + Environment.NewLine;
}
public void balance()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInf();
balance();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInf();
balance();
}
}
}
flag = false;
}
}
public void balanceKritWay()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInfKritWay();
balanceKritWay();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInfKritWay();
balanceKritWay();
}
}
}
flag = false;
}
}
public void balanceMonolit()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInfMonolit();
balanceMonolit();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInfMonolit();
balanceMonolit();
}
}
}
flag = false;
}
}
}
class Individ
{
int numbJobs;
int numbProc;
private static uint CountIndivids { get; set; }
//массив для создания расписания
//(массив рандомных чисел каждое из которых соответствует заданию)
public List<int> arrayRandom { set; get; }
public List<int> arrayTasks { set; get; }
public List<int> arrayProc;
public Proc proc;
//public Proc procKritWay;
//максимальный порог рандома
int randLimit;
int x, y;
string inf;
public int Max
{
get
{
return arrayProc.Max();
}
}
public int NumberOfJobs
{
get
{
return arrayTasks.Count;
}
}
public int NumberOfProc
{
get
{
return proc.CountProc;
}
}
public int RandomLimit
{
get
{
return randLimit;
}
}
public Individ() { }
public Individ(Individ copy)
{
arrayRandom = new List<int>(copy.arrayRandom);
arrayTasks = new List<int>(copy.arrayTasks);
//arrayProc = new List<int>(copy.arrayProc);
numbJobs = copy.numbJobs;
numbProc = copy.numbProc;
randLimit = copy.randLimit;
x = copy.x;
y = copy.y;
inf = copy.inf;
}
public Individ(int numberOfJobs, int X, int Y, int numberOfProc, int randomLimit = 255)
{
numbJobs = numberOfJobs; numbProc = numberOfProc; randLimit = randomLimit; x = X; y = Y;
arrayTasks = new List<int>(Work.arrayTask);
arrayRandom = new List<int>();
//заполнили массив рандомных чисел и работы
for (int i = 0; i < numbJobs; i++)
arrayRandom.Add(Constant.rnd.Next(0, randLimit));
proc = new Proc(numbProc);
schedule();
}
private void addInf()
{
inf = "Случайный разброс на процессоры: ";
inf += Environment.NewLine;
for (int i = 0; i < numbProc; i++)
{
inf += " Процессор " + (i + 1).ToString() + ":";
for (int j = 0; j < proc[i].Count; j++)
inf += proc[i][j] + " ";
inf += "|| sum = " + proc[i].Sum();
inf += Environment.NewLine;
}
inf += "Δ = " + proc.delta + Environment.NewLine;
}
//построить расписание
void schedule()
{
inf = string.Empty;
int k = 0;
for (int i = 0; i < proc.CountProc; i++)
proc[i].Clear();
for (int i = 0; i < NumberOfJobs; i++)
{
k = Range.rangeToIndexProc(arrayRandom[i], proc.CountProc, randLimit);
proc[k].Add(arrayTasks[i]);
}
addInf();
}
public string getRandomInString()
{
string result = string.Empty;
foreach (var iter in arrayRandom)
result += iter.ToString() + ' ';
return result;
}
public string print()
{
addInf();
return inf;
}
private int getIndexMin(List<int> list)
{
int result = 0;
for (int i = 0; i < list.Count; i++)
if (list[i] < list[result])
result = i;
return result;
}
public delegate bool sort(int x, int y);
private void sortProc()
{
arrayProc.Sort((a, b) => { return a - b; });
}
}

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Field methods in C# in the namespace

So the goal of my code is to pick two points in a grid of numbers and figure out with point gets the highest value of numbers when counting every other point in the grid closest to the two points. While typing this code I was trying to use private field variables to hold the current position of both pointers however I receive errors for the field variables I have and any calls that I make into this grid built.
namespace Program
{
private int xMe;
private int yMe;
private int zMe;
private int xEn;
private int yEn;
private int zEn;
private int dif = 0;
public class Castles
{
public static string Process(uint[,] grid)
{
int taxX = 0;
int taxY = 0;
for (int i = 0; i < grid.GetLength; i++)
{
for(int j = 0; j < grid[i]; j++)
{
for(int k = 0; k < grid.GetLength; k++)
{
for(int l = 0; l < grid[k]; l++)
{
if (distance(i, j, k, l) > 3)
{
if (grid[i, j] != 0 && grid[k, l] != 0)
{
for (int m = 0; grid.GetLength; m++)
{
for (int n = 0; grid[m]; n++)
{
if (grid[i, j] != grid[m, n] || grid[k, l] != grid[m, n])
{
if(distance(i,j,m,n) > distance(m, n, k, l))
{
taxX = taxX + distance[m, n];
}
else if(distance(i,j,m,n)< distance(m, n, k, l))
{
taxY = taxY + distance[m, n];
}
else
{
}
}
}
}
if(taxX - taxY > dif)
{
xMe = i;
yMe = j;
xEn = k;
yEn = l;
zMe = taxX;
zEn = taxY;
dif = taxX - taxY;
}
}
}
}
}
}
}
return "Your castle at (" + xMe + "," + yMe + ") earns " + zMe + ". Your nemesis' castle at (" + xEn + "," + yEn + ") earns " + zEn + ".";
}
public int distance(int x, int y, int a, int b)
{
int c = a - x;
int d = b - y;
return Math.Sqrt(c ^ 2 + d ^ 2);
}
static void Main(string[] args)
{
System.Console.WriteLine("");
}
}
}
This is my first exploration into c# so this could be a simple fix but any help would be useful
Just move the definitions of the fields to the inside of the class definition...
namespace Program
{
public class Castles
{
private int xMe;
private int yMe;
private int zMe;
private int xEn;
private int yEn;
private int zEn;
private int dif = 0;
public static string Process(uint[,] grid)
{
int taxX = 0;
int taxY = 0;
for (int i = 0; i < grid.GetLength; i++)
{
for(int j = 0; j < grid[i]; j++)
{
for(int k = 0; k < grid.GetLength; k++)
{
for(int l = 0; l < grid[k]; l++)
{
if (distance(i, j, k, l) > 3)
{
if (grid[i, j] != 0 && grid[k, l] != 0)
{
for (int m = 0; grid.GetLength; m++)
{
for (int n = 0; grid[m]; n++)
{
if (grid[i, j] != grid[m, n] || grid[k, l] != grid[m, n])
{
if(distance(i,j,m,n) > distance(m, n, k, l))
{
taxX = taxX + distance[m, n];
}
else if(distance(i,j,m,n)< distance(m, n, k, l))
{
taxY = taxY + distance[m, n];
}
else
{
}
}
}
}
if(taxX - taxY > dif)
{
xMe = i;
yMe = j;
xEn = k;
yEn = l;
zMe = taxX;
zEn = taxY;
dif = taxX - taxY;
}
}
}
}
}
}
}
return "Your castle at (" + xMe + "," + yMe + ") earns " + zMe + ". Your nemesis' castle at (" + xEn + "," + yEn + ") earns " + zEn + ".";
}
public int distance(int x, int y, int a, int b)
{
int c = a - x;
int d = b - y;
return Math.Sqrt(c ^ 2 + d ^ 2);
}
static void Main(string[] args)
{
System.Console.WriteLine("");
}
}

Weather Tracking Application

The Application has to display temperatures for five cities. I can't get the lowest and highest temperature columns to display. I got the first three columns for the temperature readings to display along with the average temperature column, but can't get the fourth temperature reading column to display. In addition, I can't get the area average label to display the area average. Any ideas?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab8practice1
{
public partial class Form1 : Form
{
string[] strCities = { "Troy",
"West Bloomfield",
"Farmington Hills",
"Brighton",
"Canton"};
int[,] intTemperatures = new int[5, 3];
public Form1()
{
InitializeComponent();
}
private void btnAddTemperature_Click(object sender, EventArgs e)
{
try
{
if (cmbCities.SelectedIndex >= 0 && cmbCities.SelectedIndex <= 4)
{
if (intTemperatures[cmbCities.SelectedIndex, (int)nudReading.Value -1] == 0)
{
intTemperatures[cmbCities.SelectedIndex, (int)nudReading.Value - 1] = Int32.Parse(txtTemperature.Text);
}
else
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show("Modify Temperature?", "Temperature already exists!", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
intTemperatures[cmbCities.SelectedIndex, (int)nudReading.Value - 1] = Int32.Parse(txtTemperature.Text);
}
}
displayTemperatures();
}
else
{
MessageBox.Show("Select a city!");
}
}
catch (FormatException)
{
MessageBox.Show("Temperatures must be whole numbers!");
}
}
private void displayTemperatures()
{
string strCities;
lstTemperatures.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
double dblNonBlank = 0.0;
int intMin = 150, intMax = 0, intTotal = 0;
for (int g = 0; g <= 4; g++)
{
intNonBlank = 0;
for (int d = 0; d <= 2; d++)
{
if (intTemperatures[g, d] != 0)
{
dblAverages[g] += intTemperatures[g, d];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[g] /= intNonBlank;
}
}
for (int g = 0; g <= 4; g++)
{
for (int d = 0; d <= 2; d++)
{
if (intTemperatures[g, d] != 0)
{
intTotal += intTemperatures[g, d];
dblNonBlank++;
}
if (intTemperatures[g, d] < intMin && intTemperatures[g, d] != 0)
{
intMin = intTemperatures[g, d];
}
if (intTemperatures[g, d] > intMax)
{
intMax = intTemperatures[g, d];
}
}
}
for (int g = 0; g <= 4; g++)
{
strCities = " ";
for (int d = 0; d <= 2; d++)
{
if (intTemperatures[g, d] == 0)
{
strCities += " ";
}
else
{
if (intTemperatures[g, d] == 103)
{
strCities += intTemperatures[g, d] + " ";
}
else
{
strCities += intTemperatures[g, d] + " ";
}
}
}
if (dblAverages[g] == 0)
{
strCities += " ";
}
else
{
if (dblAverages[g] == 140)
{
strCities += dblAverages[g].ToString("f2") + " ";
}
else
{
strCities += dblAverages[g].ToString("f2") + " ";
}
}
lstTemperatures.Items.Add(strCities);
lblAreaAverage.Text = dblAverages.ToString("f2");
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 4; i++)
{
cmbCities.Items.Add(strCities[i]);
lstCities.Items.Add(strCities[i]);
}
}
}
}

Categories