IComparable in WPF - c#

I need to implement a Search button that will compare the value from my TextBox with the values in the arrays and if they match, it returns the index, otherwise it will return -1. I implemented the random arrays of double and int already as well as all the interface and buttons. It is a must to use IComparable and CompareTo() but I have no idea on how to implement it. I tried implementing a Search method, but it is not working, I don't know how to call it in the SearchButton_Click event handler.
That's what I have so far:
public partial class MainWindow : Window
{
int[] numb = new int[6];
double[] numb2 = new double[6];
public MainWindow ()
{
InitializeComponent ();
}
//Create Int
private void Button_Click (object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear ();
resultsBox.Items.Add ("Index Value\n");
Random rnd = new Random ();
for (int i = 0; i < 6; i++) {
numb[i] = rnd.Next (0, 999);
string m = i.ToString () + "\t" + numb[i].ToString ();
resultsBox.Items.Add (m);
}
}
//Create Double
private void CreateDouble_Click (object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear ();
resultsBox.Items.Add ("Index Value\n");
Random rnd = new Random ();
for (int i = 0; i < 6; i++) {
numb2[i] = Math.Round (rnd.NextDouble () * (999), 2);
string m = i.ToString () + "\t" + numb2[i].ToString ();
resultsBox.Items.Add (m);
}
}
//Search
private void SearchButton_Click (object sender, RoutedEventArgs e) { }
static int Search<T> (T[] dataArray, T searchKey) where T : IComparable<T>
{
//Iterate through the array.
for (int iter = 0; iter < dataArray.Length; iter++) {
//Check if the element is present in the array.
if (dataArray[iter].CompareTo (searchKey) == 0) {
//Return the index if the element is present in the array.
return iter;
}
}
//Otherwise return the index -1.
return -1;
}
}
Thank you!

First you have to give the TextBox a name, so that you can reference it in your code-behind, in order to retrieve the search key. Then on button clicked, you have to check the numeric type of the search key, to identify the search target array. Then pass both arguments to the Search() method:
MainWindow.xaml
<Window>
...
<TextBox x:Name="SearchInputBox` />
...
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private readonly int arraySize = 6;
private int[] IntegerValues { get; }
private double[] DoubleValues { get; }
public MainWindow()
{
InitializeComponent();
this.IntegerValues = new int[arraySize];
this.DoubleValues = new double[arraySize];
}
// Create Int
private void Button_Click(object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear();
resultsBox.Items.Add("Index Value\n");
Random rnd = new Random();
for (int index = 0; index < arraySize; index++)
{
this.IntegerValues[index] = rnd.Next(0, 999);
string item = index.ToString() + "\t" + this.IntegerValues[index].ToString();
resultsBox.Items.Add(item);
}
}
// Create Double
private void CreateDouble_Click(object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear();
resultsBox.Items.Add("Index Value\n");
Random rnd = new Random();
for (int index = 0; index < arraySize; index++)
{
this.DoubleValues[index] = Math.Round(rnd.NextDouble() * 999, 2);
string item = index.ToString() + "\t" + this.DoubleValues[index].ToString();
resultsBox.Items.Add(item);
}
}
// Handle search button clicked
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
string numericString = this.SearchInputBox.Text;
int resultIndex = -1;
if (int.TryParse(numericString, out int integerSearchPredicate)
{
resultIndex = MainWindow.Search(this.IntegerValues, integerSearchPredicate);
}
else if (double.TryParse(numericString, out int doubleSearchPredicate)
{
resultIndex = MainWindow.Search(this.DoubleValues, doubleSearchPredicate);
}
}
static int Search<T>(T[] dataArray, T searchKey) where T : IComparable<T>
{
// Iterate over the array.
for (int index = 0; index < dataArray.Length; index++)
{
// Check if the element is present in the array.
if (dataArray[index].CompareTo(searchKey) == 0)
{
//Return the index if the element is present in the array.
return index;
}
}
// Otherwise return the index -1.
return -1;
}
}

Related

How to remove even numbers from an arraylist in c#?

So I'm trying to remove all even numbers from the generated random list I created. But this message keeps showing up: "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I don't know what I'm doing wrong. What do I need to change?
public partial class Form2 : Form
{
ArrayList array = new ArrayList();
int count = -1;
int[] numbers = new int[5];
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random randNum = new Random();
for (int i = 0; i < 5; i++)
{
numbers[i] = randNum.Next(-100, 100);
array.Add(numbers[i]);
richTextBox1.Clear();
}
for (int i = 0; i <= count; i++)
{
//displays random numbers to rich textbox
richTextBox1.AppendText(array[i].ToString() + '\n');
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (int i in array)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Your code in Button2_click is wrong. You are using foreach loop and then trying to access the index of array using its elements value.
change your second button code with following code
for (int i = 0; i < array.Count; )
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
else {
i++;
}
}
foreach (var item in array)
{
richTextBox1.Text = item +"\n";
}
You should change your enumeration like:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < array.Count; i++)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Using LINQ you can achieve this easily.
var oddArray = array.Where(a => a % 2 != 0);
richTextBox1.Text = string.Join(", ", oddArray);
PS - You just need to add a namespace i.e. System.Linq

Program that creates an array of elements obtained from actions on the first matrix and outputs the elements of the array

Create a program that finds all elements in the matrix D(m, n), where the sum of all the elements of the row standing before the one under consideration is greater than the sum of the elements of the column standing before the one under consideration. The sum of the preceding elements is considered equal to zero if the element is the first in a row or column. Form an array from the found elements. Output the matrix as a matrix, and below it output the elements of the array.(Windows Forms application)
It turns out to create the first matrix. I can't create an array according to a given rule. And I can't figure out how to output array elements(not console! its Windows Forms app)
I have been suffering for a week with this task.
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int M = 0;
int N = 0;
int[,] Numbers;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // create matrix
{
dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = true;
M = int.Parse(M_input.Text);
N = int.Parse(N_input.Text);
Numbers = new int[0, 0];
Numbers = new int[N, M];
for (int i = 0; i < M; i++)
{
dataGridView1.Columns.Add("", "");
}
for (int i = 0; i < N; i++)
{
dataGridView1.Rows.Add("", "");
}
dataGridView1.AllowUserToAddRows = false;
}
//this button should create an array and output array elements (in the form of a string, most likely)
private void button2_Click(object sender, EventArgs e)
{
int n = dataGridView1.RowCount;
int m = dataGridView1.ColumnCount;
double[,] array1 = new double[n, m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
array1[i, j] = double.Parse(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
int times = 0;
dataGridView2.RowCount = 1;
dataGridView2.ColumnCount = 0;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++)
{
double sum1 = 0;
double sum2 = 0;
if (i == 0)
sum1 = 0;
else
for (int k = 0; k < i; k++)
sum1 += array1[i, k];
if (j == 0)
sum2 = 0;
else
for (int k = 0; k < j; k++)
sum2 += array1[k, j];
if (sum1 > sum2)
{
dataGridView2.ColumnCount++;
dataGridView2.Rows[0].Cells[times].Value = array1[i, j];
times++;
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void LUM1_Click(object sender, EventArgs e)
{
}
private void LUM2_Click(object sender, EventArgs e)
{
}
private void LUM3_Click(object sender, EventArgs e)
{
}
private void Matrix_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void M_input_TextChanged(object sender, EventArgs e)
{
}
private void N_input_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Matrix2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
}
}
Imagine you have excel open, and you have numbers from 1 to 100 in a 10x10 grid.. A1 is 1, B1 is 2, A2 is 11 etc
Your assignment asks you to pick a cell, say B2. Is the sum of the values in row 1 greater than the sum of the values in column A? Yes-> put the value of B2 in a list. Repeat for another cell. Do all the cells
I started on B2 because it has a row above it and a column to the left of it so it doesn't need to handle that special case of "no row or column means means sum is 0"'that you get for any cell on row 1 or in column A
Make your life easy. Write two Methods:
public int SumColumn(int whichCol)
//if whichCol is -1 return 0
//declare variable to hold the sum
//loop over the grid from [row 0, col whichCol] to [row N, col whichCol], adding up into sum
//return sum
public int SumRow(int which)
//copy paste and adapt code above to work across rows not down columns
Now check your grid
//declare a list to hold the cells we find with SumRow>SumColumn
//for r in rows
//for c in columns
//add current cell value to a textbox ("output the matrix")
//if SumRow(r-1) > SumColumn(c-1)
//add to list
//add the contents of the list to the TextBox too with another loop
Should take about 15 minutes to write this code, not weeks. The design process for code when you're unfamiliar with anything is like I have done here. Write comments in the language you think in; get the algorithm straight in your mind and written down before you start hacking out code and getting lost. The comments are your direction, your essay plan, the recipe book while everything in the kitchen is going crazy. You absolutely have to plan your programs just like when you speak a foreign language; first you imagine the sentence you want to say in your native language, then maybe you rearrange it to how the foreigners say it (word order), then you translate the words and conjugate, modify etc, then finally you speak it. Engaging in that translation process for English->C# is the same; you know one language but not the other
When you're done, leave the comments in so if you went wrong you can either see it and fix it or your supervisor can see where your thinking and your c# understanding diverged, give you points for the algorithm and know what to teach you to help with where it went wrong
I have solved the problem
Image of matrix
namespace Matrix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int m; // columns
int n; // rows
int[,] MatrixArray; // array of matrix elements
private void Create_Click(object sender, EventArgs e)// By clicking, a matrix grid is created
{
GridMatrix.AllowUserToAddRows = true;
m = int.Parse(Size_M.Text); // Enter the number of columns
n = int.Parse(Size_N.Text); // Enter the number of rows
_Answer.Text = "Elements (answer):";
GridMatrix.Columns.Clear();
GridMatrix.Rows.Clear();
MatrixArray = new int[n, m]; // Creating an empty array of dimension m x n
for (int i = 0; i < m; i++)// Creating columns
{
GridMatrix.Columns.Add("", "");
}
for (int i = 0; i < n; i++)// Creating rows
{
GridMatrix.Rows.Add("", "");
}
GridMatrix.AllowUserToAddRows = false;
}
private void Answer_Click(object sender, EventArgs e)// When pressed, the answer appears
{
for(int i = 0; i < n; i++)// Transferring a matrix to an array
{
for(int j = 0; j < m; j++)
{
MatrixArray[i, j] = int.Parse(GridMatrix[j, i].Value.ToString());
}
}
int[] AnswerArray=new int[m*n];
int Counter=0;
for (int i = 0; i < n; i++) // The algorithm for finding elements
{
for (int j = 0; j < m; j++)
{
int RowSumm = 0,ColumnSumm=0; // Sums of row and column elements
for (int b=0;b<j;b++)// Sum of rows
{
RowSumm += MatrixArray[i, b];
}
for(int b = 0; b < i; b++)// Sum of columns
{
ColumnSumm += MatrixArray[b, j];
}
if (RowSumm>ColumnSumm)
{
AnswerArray[Counter] = MatrixArray[i, j];
Counter++;
}
}
}
_Answer.Text = "Elements (answer):";
for (int i=0;i<Counter;i++)// Output of array elements in turn
{
_Answer.Text += ""+AnswerArray[i];
if (i!=Counter-1)
{
_Answer.Text += ", ";
}
}
}
private void M_Label_Click(object sender, EventArgs e)
{
}
private void N_Label_Click(object sender, EventArgs e)
{
}
private void Answ1_Click(object sender, EventArgs e)
{
}
private void GridMatrix_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void SizeLabel_Click(object sender, EventArgs e)
{
}
private void Size_M_TextChanged(object sender, EventArgs e)
{
}
private void Size_N_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

2 x 10 random generated numbers have the same sum c#

I have 2 listboxes that i need to put 10 random generated numbers in. Then i need to calculate the sum of listbox 1 and the sum of listbox 2 and compare them to see which one is bigger. I do get different numbers in each listbox but for some reason the sum of the listboxes is always the same. How do i make it that the sum is different per listbox.
this i my code at the moment.
private void btnGo_Click(object sender, EventArgs e)
{
Random random = new Random();
listBox1.Items.Clear();
listBox2.Items.Clear();
for (int i = 0; i < 10; i++)
{
int nummer = random.Next(20);
int nummer2 = random.Next(20);
listBox1.Items.Add(nummer);
listBox2.Items.Add(nummer2);
}
if (addListbox1() > addListbox2())
{
textBox1.Text = "Listbox1 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox1());
listBox1.BackColor = Color.Green;
listBox2.BackColor = Color.Red;
}
else
{
textBox1.Text = "Listbox2 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox2());
listBox1.BackColor = Color.Red;
listBox2.BackColor = Color.Green;
}
}
private int addListbox1()
{
int listbox1total = 0;
for (int k = 0; k < listBox1.Items.Count;)
{
listbox1total += Convert.ToInt32(listBox1.Items[k++]);
}
return listbox1total;
}
private int addListbox2()
{
int listbox2total = 0;
int k = 0;
while(k < listBox2.Items.Count)
{
listbox2total += Convert.ToInt32(listBox1.Items[k++]);
}
return listbox2total;
}
You have a typo (an old story of copy + paste) in the code:
listbox2total += Convert.ToInt32(listBox1.Items[k++]);
should be
// please, notice "listBox2.Items"
listbox2total += Convert.ToInt32(listBox2.Items[k++]);
i.e. listbox2total should be the sum of listBox2.Items.
In order to avoid such errors, change the design, do not copy yourself, extract methods:
// Easiest, but not thread safe
private static Random random = new Random();
private static void FillBox(ListBox box, int count = 10) {
box.Items.Clear();
box.Items.AddRange(Enumerable
.Range(0, count)
.Select(x => (Object) random.Next(20))
.ToArray());
}
private static int SumBox(ListBox box) {
return box.Items
.OfType<Object>()
.Sum(x => Convert.ToInt32(x));
}
...
FillBox(listBox1);
FillBox(listBox2);
if (SumBox(listBox1) > SumBox(listBox2)) {
...
}

get the value from the dictionary

I am working with Round Robin (RR). I am building random Round-Robin value. I get the time for the RR randomly. In the first run it shows me the current values that i have in the list. but when it goes to run for the second time it just say the index is not presented in the dictionary key. I am trying to fix this problem I have add the time and the quantum tim that the algorithm reduce the value from the dictionary and return back to the dictionary it the value is > 0.
Dictionary<int, int> waytosave = new Dictionary<int, int>();
List<int> randomListxCoor = new List<int>();
List<int> randomListyCoor = new List<int>();
int xCoor;
int yCoor;
Random coor = new Random();
Random setTimeRandom = new Random();
int randomTimeSetting;
int NodeIndex = 0;
Graphics graphDraw;
Graphics drawLine;
int TimeToProcess = 0;
string NodeName = "";
int QuantumTime = 1;
int TotalRouterTime = 0;
int NextNodeToProcess = 0;
public Form1()
{
InitializeComponent();
this.graphDraw = this.panel1.CreateGraphics();
this.drawLine = this.panel1.CreateGraphics();
}
private void btnRun_Click(object sender, EventArgs e)
{
int nodesNumber = (int)this.numNodes.Value;
SolidBrush getNodesDrawn = new SolidBrush(Color.LightYellow);
for (int x = 1; x <= nodesNumber; x++)
{
xCoor = coor.Next(0, 700);
yCoor = coor.Next(0, 730);
if (!randomListxCoor.Contains(xCoor))
{
randomListxCoor.Add(xCoor);
}
if (!randomListyCoor.Contains(xCoor))
{
randomListyCoor.Add(yCoor);
}
randomTimeSetting = setTimeRandom.Next(1, 10);
//Draw the line from main Node to the other Nodes
Pen linePen = new Pen(Color.DarkMagenta, 2);
drawLine.DrawLine(linePen, 350, 360, xCoor, yCoor);
drawLine = this.panel1.CreateGraphics();
graphDraw.FillEllipse(getNodesDrawn, xCoor - 5, yCoor - 5, 15, 12);
//Add the values t the Dictionaries and the List.
waytosave.Add(x, randomTimeSetting);
}
}
private void btnRunTIme_Click(object sender, EventArgs e)
{
this.QuantumTime = (int)this.numQuanrum.Value;
this.ComputeTotalNodeTime();
this.timerRoundRobin.Enabled = true;
}
private void timerRoundRobin_Tick(object sender, EventArgs e)
{
this.NodeIndex = this.GetNextNodeToProcess();
if (this.NodeIndex >= 0)
{
this.waytosave[this.NodeIndex] -= this.QuantumTime;
here at this point it getting crashed. I tried to fixed the number of iteration but if i change the number of iterations it will not go through all the values in the dictionary.
if (this.waytosave[this.NodeIndex] < 0)
{
this.waytosave[this.NodeIndex] = 0;
}
this.NodeName = this.NodeIndex.ToString();
this.TimeToProcess = this.waytosave[this.NodeIndex];
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ this.TimeToProcess
+ "Router name: "
+ this.NodeName;
}
else
{
this.timerRoundRobin.Enabled = false;
this.txtOutput.Text += "\r\r\n" + " Ends x " + TotalRouterTime.ToString();
return;
}
}
private int GetNextNodeToProcess()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{ NextNodeToProcess = 0; }
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
private void ComputeTotalNodeTime()
{
this.TotalRouterTime = 0;
foreach (KeyValuePair<int, int> item in this.waytosave)
{
this.TotalRouterTime += item.Value;
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ item.Value
+ "Router name: "
+ item.Key;
}
}
I am trying to fix this value from days but i have no success. the problem that in cannot read the first value from the dictionary. How can I solve this problem. Can you please give me some Hence.

in C# is there a specific code to use to include a predetermined random number?

I am finish up my Dice roll program and have been tweaking it here and there, my program currently allows the user to roll as many times as they would like however, Ive tried using different code in order for the player to be allowed only a certain number of rolls before they get the message that they have lost all their money, for example my game should predetermine a random number lets say 9, after 9 rolls they get the message and I reset everything and game over. im a newb :(
Code from Comment
private void button1_Click(object sender, EventArgs e)
{
rollagainLabel.Visible = true;
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
int maxRolls = rand.Next(5);
for (int i = 0; i < maxRolls; i++)
if (roll1 == 1)
{
diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
Just calculate the number at the start of the program and store it in a variable, then count the number of times the player rolls and check to see if it reaches the previously calculated number.
Random rand = new Random();
int maxRolls = rand.Next(10); // 10, or whatever you want the max possible limit to be
for(int i = 0; i < maxRolls; i++)
{
roll(); // obviously this is not actual code to be used, but it gives you the structure. each roll goes inside this loop.
}
This should do the trick for you, I am checking if the maxRolls is equal to zero then creating a new Random Number, then I am checking if the rollCount is equal to maxRolls and resetting everything if it is.
public partial class Form1 : Form
{
int runningTotal;
int roll1;
int maxRolls;
int rollCount;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (maxRolls == 0)
{
Random getMax = new Random();
rollagainLabel.Visible = false;
maxRolls = getMax.Next(10) ;
}
else
if(rollCount >= maxRolls)
{
maxRolls = 0;
rollagainLabel.Visible = true;
rollCount = 0;
runningTotal = 0;
totalmoneyLabel.Text = "$0.0";
return;
}
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
rollCount += 1;
if (roll1 == 1)
{
//diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
}
I think what you want to do is to generate your random number in the Page_Load event.
After that, save that into the session, so that you can use it in your Button_Click event to compare.
Random rand = new Random();
Session["maxRolls"] = rand.Next(10);
after that, your can retrieve the value this way
int maxRolls = (int)Session["maxRolls"];
edit
Here is a sample code to tie everything together
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int minAllowableRolls = 1;
int maxAllowableRolls = 10;
Random rand = new Random();
Session["maxRolls"] = rand.Next(maxAllowableRolls - minAllowableRolls) + minAllowableRolls;
Session["rollCount"] = 0;
Session["runningTotal"] = 0;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int maxRolls = (int)Session["maxRolls"];
int rollCount = (int)Session["rollCount"];
int runningTotal = (int)Session["runningTotal"];
rollCount++;
if (rollCount < maxRolls)
{
Random rand = new Random();
runningTotal += rand.Next(6) + 1;
Label1.Text = runningTotal.ToString();
}
else
{
// Game has ended
}
Session["rollCount"] = rollCount;
Session["runningTotal"] = runningTotal;
}

Categories

Resources