How to remove even numbers from an arraylist in c#? - 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

Related

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)
{
}
}
}

How to find indexes of the most small duplicated value in a ListBox?

I tried everything i could find online and spent a lot of time on this but I cant do it.
It's a form with a ListBox with random numbers from 20 to 30 and I need to find the min and show its position. The hard part is that if i have 2 of the same number or 3 of them, then I don't know what to do and I tried almost everything.
This is the code i did so far:
Random r = new Random();
int[] a;
private void button2_Click(object sender, EventArgs e)
{
int i;
a = new int[10];
listBox1.Items.Clear();
for (i = 0; i < 10; i++)
{
a[i] = r.Next(20, 31);
listBox1.Items.Add(a[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] b;
b = new int[10];
int mini=3435, i,index=0;
b = (int[])a.Clone();
for (i = 1; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
}
}
index = Array.IndexOf(b, mini);
label2.Text = Convert.ToString("la pozitia: " + index);
label1.Text = Convert.ToString("Minimul este: " +mini );
}
This is how it should look:
Since you simply want to output the positions as a comma seperate list, you can use a separate string for the list of positions that match:
int[] b;
b = new int[10];
int mini = int.MaxValue, i, index = 0;
string miniList = "";
b = (int[])a.Clone();
for (i = 0; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
miniList = "";
}
if (b[i] == mini)
{
if (!string.IsNullOrEmpty(miniList))
{
miniList += ", ";
}
miniList += i;
}
}
label1.Text = Convert.ToString("Minimul este: " + mini);
label2.Text = Convert.ToString("la pozitia: " + miniList);
NOTE: I also set the mini value to int.MaxValue to begin with so code should work with any number range

IComparable in WPF

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;
}
}

replace last character with first character for each line in textbox using multithreading

i have 3 textbox and two button,the first textbox is to specifies (n) number of lines and character in each line,the first button will randomly generate (n) number of lines inside the second textbox,the second button will read the lines from the second textbox and then replace the last character of each line with the first character.my question is that i need to know how to do this process with using multithread(depending on the Environment.ProcessorCount)
this is my code so far:
public partial class Form1 : Form
{
static int processorCount = Environment.ProcessorCount;
Thread[] arrThr = new Thread[processorCount];
static char[][] array;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int size = Convert.ToUInt16(textBox1.Text);
textBox2.Text = null;
textBox3.Text = null;
Random random = new Random(Convert.ToInt16(DateTime.Now.Second));
array = new char[size][];
for (int i = 0; i < array.Length; i++)
{
array[i] = new char[size];
for (int j = 0; j < array[i].Length; j++)
{
array[i][j] = (char)random.Next(33, 122);
textBox2.Text += Convert.ToString(array[i][j]);
}
textBox2.Text += "\r\n";
}
}
private void button3_Click(object sender, EventArgs e)
{
var lines = new List<string>(textBox2.Lines);
for (int i = 0; i < lines.Count - 1; i++)
{
lines[i] = lines[i].Replace(lines[i].ToCharArray().Last(), lines[i].ToCharArray().First());
}
textBox3.Lines = lines.ToArray();
}
}
To begin, I think the code you posted doesn't work as expected, because the Replace method will replace all instances of one character with another one (not just the last one), so if there are other characters that match the last one in the string, then they will also be replaced.
To fix this, the code could be written something like:
for (int i = 0; i < lines.Count - 1; i++)
{
lines[i] = lines[i].Substring(0, lines[i].Length - 1) + lines[i].First();
}
To run this code in parallel, the .NET framework has the Parallel.For loop which can be leveraged:
Parallel.For(0, lines.Count - 1, i =>
{
lines[i] = lines[i].Substring(0, lines[i].Length - 1) + lines[i].First();
});

matching characters in strings in visual C#

I'm working on visual C#
to calculate the word error rate
I have one textbox for the refrence which is the correct sentance
and one for the hypothesis which is wrong one.
in order to calculate WER I need to calculate :
substitution : the word that has been changed which was my first question
Insert : the words that had been inserted in the sentence
Deleted: the words that had been deleted from the original sentence
For EX:
refrence: This is a NPL program.
hypothesis: it is an NPL cool.
it: substitution
is: correct
an :substitution
NPL:correct
program: deleted
cool: inserted
I tried the algorithm that dasblinkenlight proposed ( thank you so much by the way )
I worked but there is a runtime error I couldn't figure it out, in line
int x= Compute(buffer[j], buffer_ref[i]);
Index was outside the bounds of the array.
and here is my 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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string [] hyp = new string[20];
string [] refrence = new string[20];
string [] Anser= new string[20];
string[] buffer = new string[20];
string[] buffer_ref = new string[20];
int count = 0; // number of words
string ref2=" " ;
string hyp2 = " ";
string Anser2 = " ";
string buffer2 = " ";
int corecct_c=0;
int corecct_d = 0;
int corecct_i = 0;
//====================================================================
public Form1()
{
InitializeComponent();
for (int i = 0; i <= 19; ++i)
{
hyp[i] = null;
buffer[i] = null;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
refrence = this.textBox2.Text.Split(' ');
buffer_ref = this.textBox2.Text.Split(' ');
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
hyp = this.textBox1.Text.Split(' ');
buffer = this.textBox1.Text.Split(' ');
//hyp = this.textBox1.Text;
// fname1.Add(this.textBox1.Text);
}
public void correct(string[] R)
{
for (int i = 0; (i <= 19) && (R[i] != "."); ++i)
{
if (buffer[i] == refrence[i])
{ buffer[i] = "0";
buffer_ref[i] = "0";
corecct_c = corecct_c + 1;
Anser[i] = "C";
}
}
}
// function that compute 2 strings
public static int Compute(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
public void sub(){
for (int j = 0;j<=19;j++)
{
if (buffer[j].IndexOf("0") != -1)
{
for (int i = 0; i <= 19; i++)
{
if (buffer_ref[j].IndexOf("0") != -1)
{
int x= Compute(buffer[j], buffer_ref[i]);
if (x > 3)
{
buffer[j] = "0";
Anser[j] = "S";
}
}//end if
}
}//end if
}//end for
}// end fun
private void button1_Click(object sender, EventArgs e)
{
correct(refrence);
sub();
for (int i = 0; (i <= 19) && (refrence[i] != "."); ++i)
{
//loop intialize
ref2 = ref2 + " " + refrence[i];
hyp2 = hyp2 + " " + hyp[i];
Anser2 = Anser2 + " " + Anser[i];
buffer2 = buffer2 + " " + buffer[i];
count++;
}
listBox1.Items.Add(" Refrence :" + ref2);
listBox1.Items.Add(" HYp :" + hyp2);
listBox1.Items.Add(" Anser:" + Anser2);
listBox1.Items.Add(" buffer:" + buffer2);
listBox1.Items.Add(count);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
can you help me please ?
There is a built-in way to test if two lines are identical, but there is no built-in way to tell if two lines are similar. You need to implement an algorithm that measures string similarity, such as the Levenshtein Distance - a very common Edit Distance algorithm. Lines with small edit distance can be declared similar depending on some threshold specific to your requirements.
You'll need to use an algorithm that compares the "distance" between two strings:
The closeness of a match is measured in terms of the number of
primitive operations necessary to convert the string into an exact
match. This number is called the edit distance between the string and
the pattern. The usual primitive operations are:
insertion: cot → coat
deletion: coat → cot
substitution: coat → cost

Categories

Resources