I have a problem (as seen in the screenshot below) where my chart in Visual C# looks great, but I'd like to remove the first and last axis interval label on the X-Axis (specifically the "3750" and "98250" in my bar chart).
In other words, these two labels shouldn't be visible/show nothing.
Code:
private void btnRun_Click(object sender, EventArgs e)
{
double numIter, PvMean, PvStDev = 0;
int nMin, nMax, numBins = 0;
//NOTE: n is # vehicles sold; numBins is # of bins
numIter = double.Parse(txtNumIter.Text);
numBins = int.Parse(txtNumBins.Text);
PvMean = double.Parse(txtMean.Text);
PvStDev = double.Parse(txtStDev.Text);
nMin = int.Parse(txtMin.Text);
nMax = int.Parse(txtMax.Text);
//+- 3 st devs
PvMin = ((-3) * PvStDev) + PvMean;
PvMax = (3 * PvStDev) + PvMean;
PtMin = nMin * PvMin;
PtMax = nMax * PvMax;
//Bin array
int [] Bins = new int[numBins+1];
Random nPv = new Random();
double Pt, totalprofit = 0;
int Pv, n = 0;
int i = 0;
for(i=0; i < numIter ; i++)
{
//Use these vars to be able to produce random numbers
int PvMinRand = Convert.ToInt32(PvMin);
int PvMaxRand = Convert.ToInt32(PvMax);
n = nPv.Next(nMin, (nMax + 1));
Pv = nPv.Next(PvMinRand, (PvMaxRand + 1));
//Equation for random Pv and n to get Pt
Pt = n * Pv;
//Increments total profit;
totalprofit += Pt;
//Bin index from rand
int index = 0;
//Call GetBinIndex method
index = GetBinIndex(PtMin, PtMax, numBins, Pt);
//Incremenents bin count by 1
Bins[index] += 1;
}
//Increment of chart
double Increment, incrCount, binRange = 0;
binRange = PtMax - PtMin;
Increment = binRange / numBins;
chtSim.ChartAreas[0].AxisX.Interval = Increment;
//Graph bars for each bin loop
int j = 1;
for (j = 1; j < (numBins+1); j++)
{
//Increases incr label value for each iteration above Pt Min
incrCount = Increment * j + PtMin;
//Graph bar for each index
chtSim.Series[0].Points.AddXY(incrCount, Bins[j]);
}
You can set the AxisLabel individually for each DataPoint.
By doing so, the automatic labels get removed. So you can write.:
int ix = chtSim.Series[0].Points.AddXY(incrCount, Bins[j]);
chtSim.Series[0].Points[ix].AxisLabel = incrCount;
.. in your loop.
Now only those labels you have set yourself are shown.
Related
Here's my code for one of the algorithm given by our professor. Everything is working fine except the last part of the program. I have to divide each element of the Statistics array by NumberofExperiments and assign that value to another array Frequency. But it's not happening so. The values assigned to Frequency array is always zero. I have debugged the code and array Statistics has all the elements. So there's a problem only in the last part of the program. Any kind of help is appreciated.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] Statistics = new int[5];
double P1;
double P2;
double P3;
double P4;
double P5;
int NumberofExperiments;
double SumofP;
Random random = new Random();
int k;
private void button1_Click(object sender, EventArgs e)
{
P1 = Convert.ToDouble(textBox1.Text);
P2 = Convert.ToDouble(textBox2.Text);
P3 = Convert.ToDouble(textBox3.Text);
P4 = Convert.ToDouble(textBox4.Text);
NumberofExperiments = Convert.ToInt32(textBox6.Text);
SumofP = P1 + P2 + P3 + P4;
P5 = 1 - SumofP;
textBox5.Text = P5.ToString();
int i;
for( i = 0; i <= NumberofExperiments;)
{
if (i < NumberofExperiments)
{
k = random.Next(0, 5);
Statistics[k] = Statistics[k] + 1;
i++;
}
else
{
double[] Frequency = new double[5]; //initializing an empty array
for(int j = 0; j < 5; j++)
{
Frequency[j] = Statistics[j] / NumberofExperiments; //The Problem is here.
textBox7.Text = Frequency[j].ToString();
}
break;
}
}
}
}
You initialise a new array every loop,
Statistics is of type int. Cast it to double:
for(int j = 0; j < 5; j++)
{
Frequency[j] = Statistics[j] / NumberofExperiments; //The Problem is here.
textBox7.Text = Frequency[j].ToString();
}
you essentially empty the array every iteration. Take that outside of the loop, cast the division and it should be fine. Also to display all of the values and not just the last, you must ADD to the text of the textBox and not replace it entirely.
double[] Frequency = new double[5]; //Now its fine
for(int j = 0; j < 5; j++)
{
Frequency[j] = (double)Statistics[j] / NumberofExperiments;
textBox7.Text = textBox7.Text + " " + Frequency[j].ToString();
}
I am having issues with the output of the the result of a math calculation. I have a basic average of an array of double and I assign the result to a Label object, using the ToString() method. When I emulate the average, the label shows the correct value of 15.96 for example, but the same average of the same array, on my Galaxy S3 shows 159.6.
Is there anyone who know what's up and what can I do to make the S3 show the correct value?
Thank you all!
EDIT: passing the result to a label and adding the label to the grid:
double result = Math.Round(NP122.DoAverage(parameters), 2);
CustomLabel label = new CustomLabel();
label.ColNo = grid.ColumnDefinitions.IndexOf(c);
label.FontSize = 25;
label.TextColor = Color.Green;
if (result.ToString() == "NaN")
label.Text = "0";
else
label.Text = result.ToString();
label.IsVisible = true;
for (int i = 0; i < numberOfRows.Length + 2; i++) {
if(i == numberOfRows.Length +1)
Grid.SetRow(label, i);
}
Grid.SetColumn(label, grid.ColumnDefinitions.IndexOf(c));
listaRez.Add(label);
foreach (CustomLabel a in listaRez)
{
if (a.ColNo == grid.ColumnDefinitions.IndexOf(c))
{
grid.Children.Add(a);
}
}
EDIT 2: Custom function for NP122.DoAverage:
public static class NP122
{
public static double Vx, sx, Xm, kn, Xkinf, Xksup;
public static double sum;
public static double sumaProvizorie;
public static double[] valoriKn = new double[25];
public static double ValoareCaracteristicaSuperioara(double[] l)
{
Vx = 0;
sx = 0;
Xm = 0;
kn = 0;
Xkinf = 0;
Xksup = 0;
sum = 0;
sumaProvizorie = 0;
valoriKn[0] = 0;
//more here
valoriKn[24] = 0.35;
if (l.Length < 2 )
{
Xksup = 0;
Xkinf = 0;
}
else
{
Xm = (l.Sum()) / (l.Length);
for (int j = 0; j < l.Length; j++)
{
sumaProvizorie = Math.Round(Math.Pow((l[j] - Xm), 2), 2);
sum += sumaProvizorie;
}
kn = valoriKn[l.Length - 1];
double elements = (1.00 / (l.Length - 1));
double putere = sum;
sx = Math.Round(Math.Sqrt(elements * putere), 4);
Vx = sx / Xm;
Xksup = Xm * (1 + kn * Vx);
Xkinf = Xm * (1 - kn * Vx);
}
return Xksup;
First of all, I'm a rookie in programming and I'm not English, I'm sorry if I had a mistake expressing myself :D
I'm doing a program that represents a booking system bus. I had created 64 buttons at Runtime with an array of buttons, but that isn't the problem.
The problem is to represent each text button corresponding to the number of seats of the bus. Here is my code:
var buttonArray = new Button[64];
for (var i = 1; i <= 4; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(75, 23);
buttonArray[i].Name = "button" + i;
buttonArray[i].Text = "Seat " + i;
buttonArray[i].Location = new Point(-50 + (i*100), 10);
panel1.Controls.Add(buttonArray[i]);
for (var j = 5; j <= 19; j++)
{
buttonArray[j] = new Button();
buttonArray[j].Size = new Size(75, 23);
buttonArray[j].Name = "button" + j;
buttonArray[j].Text = "Seat " + j;
buttonArray[j].Location = new Point(-50 + (i * 100), -105 + (j * 30));
panel1.Controls.Add(buttonArray[j]);
}
}
The result would be 64 buttons represented with 4 columns and 16 rows, for example:
Here's how I would do it: Just loop from zero to 63, and calculate the row and column on the fly. Then you set the button properties and add it to the panel. You can change the size of the seats by adjusting the seatWidth and seatHeight variables. Also note that I added a little extra space between the first two columns and the second two columns, because it looks like that's what you had in your diagram. You can adjust this with the middleRowWidth variable. You can also customize the distance between the seats by adjusting the seatSpacing value:
const int seatSpacing = 4;
const int middleRowWidth = 20;
const int seatWidth = 55;
const int seatHeight = 20;
panel1.Width = 4 * (seatWidth + seatSpacing) + seatSpacing + middleRowWidth;
var buttonSize = new Size(seatWidth, seatHeight);
for (var i = 0; i < 64; i++)
{
// Calculate the location for this seat
int thisRow = i / 4;
int thisColumn = i % 4;
int seatTop = thisRow * (seatHeight + seatSpacing);
int seatLeft = thisColumn * (seatWidth + seatSpacing);
// Add some extra distance down the middle
if (thisColumn >= 2) seatLeft += middleRowWidth;
// Create a new button
var thisButton = new Button
{
Size = buttonSize,
Name = "button" + (i + 1),
Text = "Seat " + (i + 1),
Location = new Point(seatLeft, seatTop),
Visible = true,
};
// Add it to the panel
panel1.Controls.Add(thisButton);
}
Result:
UPDATE
After thinking about how to make this more generic, I thought about how some airplanes have their seats laid out. Some have two seats on each side, some have three, some have two on each side with a column of three down the middle. In order to accommodate different types of layouts, I modified the code slightly. Below code has customizable variables for your layout. The one below is for a 2-3-2 layout, where the numbers are the seat count and - are aisles. It also includes two "exit row" aisles running horizontally:
// Seating Layout
const int numberOfRows = 20;
const int numberOfColumns = 7;
const int numberOfSeats = numberOfRows * numberOfColumns;
var columnsToInsertAisleAfter = new List<int> {1, 4};
var rowsToInsertAisleAfter = new List<int> {6, 12};
// Seat sizing
const int seatWidth = 35;
const int seatHeight = 20;
const int seatSpacing = 4;
const int aisleWidth = 20;
var seatSize = new Size(seatWidth, seatHeight);
// Panel and form layout
panel1.Size = new Size(
numberOfColumns * (seatWidth + seatSpacing) + seatSpacing +
aisleWidth * columnsToInsertAisleAfter.Count,
numberOfRows * (seatHeight + seatSpacing) + seatSpacing +
aisleWidth * rowsToInsertAisleAfter.Count);
this.Size =
new Size(panel1.Size.Width + (panel1.Left * 2),
panel1.Size.Height + (panel1.Top * 2)) +
new Size(this.Width - this.ClientSize.Width,
this.Height - this.ClientSize.Height);
// Add seats to panel
for (var i = 0; i < numberOfSeats; i++)
{
// Calculate the location for this seat
int thisRow = i / numberOfColumns;
int thisColumn = i % numberOfColumns;
int seatTop = thisRow * (seatHeight + seatSpacing);
int seatLeft = thisColumn * (seatWidth + seatSpacing);
// Add some extra distance for aisles
var aislesBeforeThisColumn =
columnsToInsertAisleAfter.Count(col => col < thisColumn);
seatLeft += aislesBeforeThisColumn * aisleWidth;
var aislesBeforeThisRow =
rowsToInsertAisleAfter.Count(row => row < thisRow);
seatTop += aislesBeforeThisRow * aisleWidth;
// Add a new button to the panel
panel1.Controls.Add(new Button
{
Size = seatSize,
Name = "button" + (i + 1),
Text = (i + 1).ToString(),
Location = new Point(seatLeft, seatTop),
Visible = true,
});
}
Large Airplane Layout:
This should do what you want,
Point pt;
int y = 20;
int x = 0;
for (int i = 0; i < 16; i++)
{
x = 20;
for (int j = 1; j <= 4; j++)
{
pt = new Point(x, y);
Button btn = new Button() { Location = pt, Size = new Size(75, 23) };
btn.Name = i.ToString() + j.ToString();
btn.Text = string.Format("{0} {1:D2}", "Seat", i * 4 + j);
panel1.Controls.Add(btn);
x += 90;
}
y += 30;
}
I'm trying to XOR each letter from my TextBox with each value from my array.
The problem is, that when I convert double to int array, my int array result stores only one value.
If I run my code I get first letter XORed, but if I input more then one, I get message :
System.IndexOutOfRangeException: Index was outside the bounds of the array.
I have tried myself to create an int array like: int[] result = new int[] {1,2,3,4,5,6,7}; and I didn't have any problems with XORing up to 7 letters..
private void iTalk_Button_12_Click(object sender, EventArgs e)
{
ambiance_RichTextBox1.Text = XorText(ambiance_RichTextBox1.Text);
}
private string XorText(string text)
{
string newText = "";
double r = 3.9;
double[] first_value = new double[text.Length];
double[] to_int_array = new double[text.Length];
for (int i = 0; i < text.Length; i++)
{
double get_first = r * i * (1 - i);
int index = (int)(i * text.Length);
first_value[index] = get_first;
}
for (int i = 0; i < text.Length; i++)
{
int xnbb = 0;
if (first_value[i] > Math.Exp(Math.Log(2) * (-i)))
{
double get_first = first_value[i] - Math.Exp(Math.Log(2) * (-i));
xnbb = 1;
}
double array_of_values = xnbb + 1 * Math.Round(Math.Exp(Math.Log(2) * (24 - i)));
int index = (int)(i * text.Length);
to_int_array[index] = array_of_values;
int[] result = new int[] { Convert.ToInt32(to_int_array[i]) };
int charValue = Convert.ToInt32(text[i]);
charValue ^= result[i]%320;
newText += char.ConvertFromUtf32(charValue);
}
return newText;
}
double[] first_value = new double[text.Length];
...
for (int i = 0; i < text.Length; i++)
{
double get_first = r * i * (1 - i);
int index = (int)(i * text.Length);
first_value[index] = get_first;
}
When the text length is 2, first_value index may run from 0..1. i will loop from 0 to 1. the calculated index becomes 1 x 2 = 2, and that is beyond the index range.
When passing a string with 2 characters to XorText, the System.IndexOutOfRangeException is thrown in this Line:
first_value[index] = get_first;
because the index is 2 when the loop body is executed the second time:
int index = (int)(i * text.Length);
You really should consider learning how to use a debugger. It will make programming easier.
I need to sort a list of points by distance.
So for e.g.
input : [[1,2],[5,10],[2,4]...]
output : [[1,2],[2,4],[5,10]...]
(assuming that geometrically [1,2] and [2,4] are nearest & [2,4] & [5,10] are nearest.
I need them to sort it so they are ordered by distance i.e. on the geometrical graph, point a is nearest to point b , point b is nearest to c and so on.
Any idea?
Edit: Code example
public class Point
{
public double X {get;set;}
public double Y {get;set;}
}
List<Point> points = new List<Point>();
let say my points list is getting populated in random order (not by geometrical distance).
So points would look something like...
point ~ [[1,2],[5,10],[2,4]...]
Now my charting control just take the first & second point and draw a line between them. Which means it does not care which geometrical order is it in.
If I simply supply the "points" list as above its going to draw lines between each points and from charting point of view it would not look correct as they would be "zig-zag".
To make sure the charting control draws a straight line (& and not zig-zag) I have to pass the points in the right order which would look something like ...
destination points ~ [[1,2],[2,4],[5,10]...]
So my question is how to achieve this.
Note: Changing chart control is not an option here.
Thanks
The code first takes the nearest point to (0, 0) at the '0' index then start sorting the points by distance from the last spotted point..
C#:
List<Point> SortByDistance(List<Point> lst)
{
List<Point> output = new List<Point>();
output.Add(lst[NearestPoint(new Point(0, 0), lst)]);
lst.Remove(output[0]);
int x = 0;
for (int i = 0; i < lst.Count + x; i++)
{
output.Add(lst[NearestPoint(output[output.Count - 1], lst)]);
lst.Remove(output[output.Count - 1]);
x++;
}
return output;
}
int NearestPoint(Point srcPt, List<Point> lookIn)
{
KeyValuePair<double, int> smallestDistance = new KeyValuePair<double, int>();
for (int i = 0; i < lookIn.Count; i++)
{
double distance = Math.Sqrt(Math.Pow(srcPt.X - lookIn[i].X, 2) + Math.Pow(srcPt.Y - lookIn[i].Y, 2));
if (i == 0)
{
smallestDistance = new KeyValuePair<double, int>(distance, i);
}
else
{
if (distance < smallestDistance.Key)
{
smallestDistance = new KeyValuePair<double, int>(distance, i);
}
}
}
return smallestDistance.Value;
}
VB.Net:
Function SortByDistance(ByVal lst As List(Of Point)) As List(Of Point)
Dim out As New List(Of Point)
out.Add(lst(NearestPoint(New Point(0, 0), lst)))
lst.Remove(out(0))
Dim x As Integer = 0
For i As Integer = 0 To lst.Count - 1 + x
out.Add(lst(NearestPoint(out(out.Count - 1), lst)))
lst.Remove(out(out.Count - 1))
x += 1
Next
Return out
End Function
Function NearestPoint(ByVal srcPt As Point, ByVal lookIn As List(Of Point)) As Integer
Dim smallestDistance As KeyValuePair(Of Double, Integer)
For i As Integer = 0 To lookIn.Count - 1
Dim distance As Double = Math.Sqrt(Math.Pow(srcPt.X - lookIn(i).X, 2) + Math.Pow(srcPt.Y - lookIn(i).Y, 2))
If i = 0 Then
smallestDistance = New KeyValuePair(Of Double, Integer)(distance, i)
Else
If distance < smallestDistance.Key Then
smallestDistance = New KeyValuePair(Of Double, Integer)(distance, i)
End If
End If
Next
Return smallestDistance.Value
End Function
I think you want this, Dijkstra's algorithm. There is a c# project here.
What follows is unmodified code from that link
class Dijkstra
{
private int rank = 0;
private int[,] L;
private int[] C;
public int[] D;
private int trank = 0;
public Dijkstra(int paramRank,int [,]paramArray)
{
L = new int[paramRank, paramRank];
C = new int[paramRank];
D = new int[paramRank];
rank = paramRank;
for (int i = 0; i < rank; i++)
{
for (int j = 0; j < rank; j++) {
L[i, j] = paramArray[i, j];
}
}
for (int i = 0; i < rank; i++)
{
C[i] = i;
}
C[0] = -1;
for (int i = 1; i < rank; i++)
D[i] = L[0, i];
}
public void DijkstraSolving()
{
int minValue = Int32.MaxValue;
int minNode = 0;
for (int i = 0; i < rank; i++)
{
if (C[i] == -1)
continue;
if (D[i] > 0 && D[i] < minValue)
{
minValue = D[i];
minNode = i;
}
}
C[minNode] = -1;
for (int i = 0; i < rank; i++)
{
if (L[minNode, i] < 0)
continue;
if (D[i] < 0) {
D[i] = minValue + L[minNode, i];
continue;
}
if ((D[minNode] + L[minNode, i]) < D[i])
D[i] = minValue+ L[minNode, i];
}
}
public void Run()
{
for (trank = 1; trank >rank; trank++)
{
DijkstraSolving();
Console.WriteLine("iteration" + trank);
for (int i = 0; i < rank; i++)
Console.Write(D[i] + " ");
Console.WriteLine("");
for (int i = 0; i < rank; i++)
Console.Write(C[i] + " ");
Console.WriteLine("");
}
}
}
In a graph, a set of points (x1,y1), (x2,y2), (x3,y3)...(xn,yn) should be ordered on the value of any one co ordinate because it is not the nearest point that should come next in order, but the one with nearest x or y (whichever axis is taken as reference) co-ordinate value. So, the array to pass for charting should be:
var orderedPoints=points.OrderBy(p=>p.X);
In the above image, the length of the line L1 is greater than L2. But the point P2 and not P3 should be come after P1 since P2.X<P3.X