I try to follow the code here:
C# Finding Nearest Number in Array
but fail.
The only different from my code with the code there is in my code the MinBy is error (there is red underline) which show its an error in Visual Studio.
By the way, this is the the code that I write:
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double[] array = new double[5] { 0.25, 0.4, 0.5, 0.6, 0.7 };
double TargetNumber = Double.Parse(textBox1.Text);
var nearest = array.MinBy(x => Math.Abs((long)x - targetNumber));
label1.Text = nearest.ToString();
}
}
}
Im new with C# things. Sorry for a noob question.
Thanks in advance.
You overcomplicate things. Here is your "bread-and-butter" helper method which finds the value from array a nearest to the passed value d:
private static double? FindNearestValue(IEnumerable<double> arr, double d)
{
var minDist = double.MaxValue;
double? nearestValue = null;
foreach (var x in arr)
{
var dist = Math.Abs(x - d);
if (dist < minDist)
{
minDist = dist;
nearestValue = x;
}
}
return nearestValue;
}
To use it:
private void button1_Click(object sender, EventArgs e)
{
double[] array = new double[5] { 0.25, 0.4, 0.5, 0.6, 0.7 };
double TargetNumber = Double.Parse(textBox1.Text);
var nearest = FindNearestValue(array, TargetNumber);
label1.Text = nearest.ToString(); // nulls are printed as empty string
}
For small arrays linear search has comparable speed to the binary search. If implementing binary search is problem for you and you're new to c# (didn't get used to LINQ power) then good-ol' foreach is your friend for now.
Sometimes implementing a library to use just one method sounds a little bit like an overkill (even if MoreLINQ is an amazing library)... this code should provide you the same result without using an external library, if it's a good solution for you:
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Double[] array = new Double[] { 0.25, 0.4, 0.5, 0.6, 0.7 };
Double targ = Double.Parse(textBox1.Text);
Double[] arraySorted = array.OrderBy(x => Math.Abs(x - targ)).ToArray();
Int32 idx = Array.IndexOf(array,arraySorted.First());
label1.Text = idx.ToString();
Double arrayValue = array[idx];
Int32 idxLower = 0;
Int32 idxUpper = 0;
if (targ == arrayValue)
idxLower = idxUpper = idx;
else
{
if (targ > arrayValue)
{
idxLower = idx;
idxUpper = idx + 1;
}
else
{
idxLower = idx - 1;
idxUpper = idx;
}
}
label2.Text = idxLower.ToString();
label3.Text = idxUpper.ToString();
}
}
}
Related
For example, I need richTextBox2 to print whatever is in between "AaBb" and "CcDd" at richTextBox1.
if (richTextBox1.Text.Contains ("AaBb x CcDd"))
//print whatever is x in richTextBox2
Edit: I forgot to mention what i'm trying to do. I´m trying to scrape a website and print the value in the richTextBox (Euro to Dollar for example).
This is my code so far. Unfortunnaly, it doesn't work on both answers.
Version 1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net;
using System.Windows.Forms;
namespace BitPrice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebClient priceVariationDollar = new WebClient();
string dollarPrice = priceVariationDollar.DownloadString("https://www.xe.com/pt/currencyconverter/convert/?Amount=1&From=EUR&To=USD");
euroTextBox.Text = dollarPrice;
if (euroTextBox.Text.Contains("<span class=converterresult - toAmount></span>"));
{
int p1, p2;
p1 = euroTextBox.Text.IndexOf("<Span class=converterresoult - toAmount>");
p2 = euroTextBox.Text.IndexOf("</span>");
if (p2 > p1 + 4)
{
dollarTextBox.Text = euroTextBox.Text.Substring(p1 + 4, p2 - p1 - 4);
}
}
}
}
Version 2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net;
using System.Windows.Forms;
namespace BitPrice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebClient priceVariationDollar = new WebClient();
string dollarPrice = priceVariationDollar.DownloadString("https://www.xe.com/pt/currencyconverter/convert/?Amount=1&From=EUR&To=USD");
euroTextBox.Text = dollarPrice;
if (euroTextBox.Text.Contains("<span class=converterresult - toAmount></span>"));
{
var startIndex = euroTextBox.Text.IndexOf("<span class=converterresult - toAmount>") + "<span class=converterresult - toAmount>".Length;
var endIndex = euroTextBox.Text.IndexOf("</span>");
if (startIndex >= 0 && endIndex > startIndex)
dollarTextBox.Text = euroTextBox.Text.Substring(startIndex, endIndex - startIndex);
}
}
}
Sorry if it´s too long
var startIndex = richTextBox1.Text.IndexOf("AaBb") + "AaBb".Length;
var endIndex = richTextBox1.Text.IndexOf("CcDd");
if (startIndex >= 0 && endIndex > startIndex)
richTextBox2.Text = richTextBox1.Text.Substring(startIndex, endIndex - startIndex);
You will need to first check whether these two text are in richTextBox1, then if they both exit, you see if the first one comes before the second, then you take what is between.
int p1, p2;
string t1, t2;
t1 = "....."; //Your first searched text
t2 = "..."; //Your second searched text
p1 = richTextBox1.Text.IndexOf(t1);
p2 = richTextBox1.Text.IndexOf(t2);
if (p2 > p1 + t1.Length)
richTextBox2.Text1 = richTextBox1.Text.Substring(p1 + t1.Length, p2 - p1 - t1.Length);
I have a very small windows form application that calculates the storage cost for a warehouse depending on the amount of deliveries per year and presents the result in form of a chart.
It's doing what it's supposed to do, but there is just one little flaw.
There is 13 columns in the first bit and then there is 12 every other time.
I want it to always be 12.
I've been trying to reorder some lines of code, it looks like it's all ok, I'm probably just missing one line of code but can't figure it out
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 StorageCost
{
public partial class Form1 : Form
{
public static int throughPot = 52000;
public static int weekly = 1000;
public static int weeklyPalletCost = 180;
public static int deliveries = 2;
public int storageCost;
public static int x = 0;
public static int currentPot = throughPot / deliveries;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
currentPot = throughPot / deliveries;
storageCost = 0;
x = 0;
chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
for (int i = 1; i < 51; i++)
{
currentPot -= weekly;
if (x>= 51 / deliveries)
{
x = 0;
currentPot = throughPot / deliveries;
}
chart1.Series[0].Points[i].YValues[0] = currentPot + 4000;
storageCost += currentPot * weeklyPalletCost;
x++;
}
cost.Text = "Total storage cost: £" + storageCost / 100;
chart1.ChartAreas[0].RecalculateAxesScale();
chart1.Update();
}
private void deliveriesUpDown_ValueChanged(object sender, EventArgs e)
{
deliveries = (int)deliveriesUpDown.Value;
Calculate();
}
}
}
this is the full code.
all I need basically is to get the same result in the beginning as from 13th column onwards
any help will be much appreciated.
thanks in advance.
It was because the first column was done outside of the for loop!
after commenting this out
//currentPot = throughPot / deliveries;
//storageCost = 0;
//x = 0;
//chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
and changing the loop to for (int i = 0; i < 51; i++)
I got it to work as expected.
Thanks #Grimm
I didn't know about this F11, F10 thing. This helped me a lot!
I am new to C# and random number generators, but need to code a simulator for a course I am taking. I am having difficulty with my for loop and my user-defined variables. I am coding in Visual Studio and need the user to select a number from a list (or input the number as text), but for the program to read it as an integer, not a string, and then use this integer as the number of times to generate a random number.
I will need to assign a probability distribution to this random number generator later, but right now I just need the thing to run! I am getting an error that it cannot covert int to string (or visa versa depending on how I code it). As well as getting an error that my local variable i is unassigned. I have looked at others codes for similar generators and I cannot see a difference in my for loop. Please help! Below is the form space C# code:
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 GenerateProfile
{
public partial class Form1 : Form
{
int N;
public Form1()
{
InitializeComponent();
}
private void ChooseN_SelectedIndexChanged(object sender, EventArgs e)
{
N = ChooseN;
}
private void SBtn_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(0, 100);
pi.Text = num.ToString();
for (int i; <= N; i++)
{
num = rnd.Next(0, 100);
pi.Text = pi.Text + num.ToString();
}
}
private void ClBtn_Click(object sender, EventArgs e)
{
Close();
}
}
}
I figured it out myself. I was not reading in ChooseN correctly. This fixed it.
private void Gen_Click(object sender, EventArgs e)
{
MessageBox.Show("N=", this.txtN.Text);
N = Convert.ToInt32(txtN.Text);
Random rnd = new Random();
int num = rnd.Next(-1, 1);
pitxt.Text = num.ToString();
int[] = { num };
for (int i = 1; i <= N; i++)
{
num = rnd.Next(-1, 1);
pitxt.Text = pitxt.Text + "," + num.ToString();
int[] = { int[], num };
}
I'm in trouble on a College project.The project needs to be done using c# as a programming language and made in Windows Form like.
The program executes. I know it has flaws but at least i want to know how to get of this error: http://postimg.org/image/gwuzmyc73/ .
For the problem i need to fold a vector using the Divide et Impera.
I need to insert a number from the keyboard n, the generated vector would be like a=(1,2,3,4,5,6,7) and the final elements are 1,3,5,7.
The problem sounds like:
A vector of n elements.We define its folding by overlaping the 2 halfs,if n is odd.The 2 halfs are folded again until de subvector reaches 1 element.Utilize Divide et Impera.
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 Plierea_Vectorilor
{
public partial class Form1 : Form
{
public int n;
public int i;
public int[] efinal = new int[50];
public string m = new string(new char[50]);
public int Ls, Ld;
public char[] aux = new char[50];
public Form1()
{
InitializeComponent();
}
public void Pliaza(int p,int q)
{
if (p == q)
{
efinal[p] = 1;
}
else
{
if ((q - p + 1) % 2 != 0)
{
Ls = (p + q) / 2 - 1;
}
else
{
Ls = (p + q) / 2;
}
Ld = (p + q) / 2 + 1;
}
Pliaza(p, Ls);
Pliaza(Ld, q);
/*
string ss = Ls.ToString();
string sd = Ld.ToString();
for (i = p; i <= Ls; i++)
{
aux[0] = 'S';
string.Concat(aux, ss);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
for ( i = Ld; i <= q; i++)
{
aux[0] = 'D';
string.Concat(aux,Ld);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
*/
}
private void button1_Click(object sender, EventArgs e)
{
Pliaza(1, n);
for (i = 1; i <= n; i++)
{
if (efinal[i]!=0)
{
label2.Text = Convert.ToString(i);
}
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
You're ALWAYS executing the Pliaza function FROM Pliaza. Aren't you missing a finish condition?
The recursive loop must be finished sometime in someway, else you will get that stack overflow.
A StackOverflowException usually means you have uncontrolled recursion going on. Reviewing your code, I see that Pliaza calls itself twice, using different variables ... but there is no path for Pliaza to exit without calling itself. You need some path to let the recursion bottom out. Very likely this would be to add a return; statement after the efinal[p] = 1; line.
My test function as follows:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
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;
using System.Collections;
namespace ex4
{
[TestClass]
public class UnitTest1
{
public double result = 0.0;
computation co = new computation();
public void valuereq()
{
Stream myStream = null;
var openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\Hassan Qamar\Desktop\share market research paper\experiment folder";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string path = openFileDialog1.FileName;
var readstream = new StreamReader(myStream);
readstream.Close();
string[] datatoprint = File.ReadAllLines(#path);
result = co.LaggedCorrelation(datatoprint);
Console.WriteLine(result);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(9.8,result,0.5);
}
}
}
I am extracting value from .csv file and passing it for computation.
The expected result should be 9.6 approx. But while testing it showing 0 in assert function.
Computation class as follows:
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace ex4
{
public class computation
{
Form1 f = new Form1();
public double output;
public double LaggedCorrelation(string[] datatoprint)
{
List<double> laggedCorrelation = new List<double>();
int cond = 0;
double n = datatoprint.Length - 1;//removing header row
double xsum = 0.0, ysum = 0.0, x = 0.0, y = 0.0, xy = 0.0, xsquare = 0.0, ysquare = 0.0;
// while (cond < 2)
// {
// double output = 0.0;
double numerator = 0.0, denominator = 0.0;
foreach (var l in datatoprint.Skip(1))
{
string[] s = l.Split(',');
x = Convert.ToDouble(s[cond]); y = Convert.ToDouble(s[cond +1]);
xsum += x; ysum += y;
xy += x * y;
xsquare += x * x; ysquare += y * y;
}
cond++;
numerator = (n * (xy)) - (xsum * ysum);
denominator = (Math.Sqrt(n * xsquare - xsum * xsum)) * (Math.Sqrt(n * ysquare - ysum * ysum));
output = numerator / denominator;
laggedCorrelation.Add(output);
return output;
}
}
}
Computation function give the lagged correlation between 2 given stock.when I work without testing I get the value as required otherwise in test function.
Output remain 0.
You are not calling the valuereq() method inside your Test Method. So it is taking the initial value which is 0 as you assigned on the top public double result = 0.0;
Anyway, try this
[TestMethod]
public void TestMethod1()
{
valuereq();
Assert.AreEqual(9.8,result,0.5);
}
By the way, you don't have to rewrite the actual method in TestClass, all you have to do is create an object of the actual class contains your actual method, and call it inside your TestMethod.
Edit: Assert.AreEqual method should take two parameters result and your expected result, in your case 9.6. So it must be Assert.AreEqual(9.6,result); to get your unit test pass.
The result is 0.0 because you never modify it from the initialized value.
public double result = 0.0; // <-- never changes again.
More plainly you never use what you're testing.
Generally, you want to write a unit test something like this:
[TestMethod]
public void AssertFooHasAWidget() {
// Setup
var foo = new Foo(); // or better, mocking a Foo
// Act
foo.giveWidget();
// Assert
Assert.IsTrue(foo.hasWidget());
}
Other notes:
The input to your test doesn't need to change. If it does, then you don't know if a later success (or failure) is because of the change in input, or a breaking (or fixing!) change in your code.