How to print stars depending on value of an array? - c#

I recently make a program to calculate sum and avg of a given array. The program also want to print the histogram or stars pattern match with value of index.
Like this:
This is the code I wrote so far:
private void process_Click(object sender, EventArgs e)
{
string temp2 = null;
string temp3 = null;
float sum=0;
int countingNumber = 1;
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i = 0; i < count; i++)
//for (int j = 1; j <= count; j++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message = "enter the value of array number " + countingNumber));
sum = sum+ varray[i];
temp += countingNumber + " "+varray[i] + Environment.NewLine;
temp2 += countingNumber + " " + varray[i] + " *" + Environment.NewLine;
box1.Text = Convert.ToString("Index Value" + Environment.NewLine + temp);
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum/count);
countingNumber++;
}
for (int stars = 0; stars <= i; stars++)
{
temp3 = " ";
box2.Text = Convert.ToString("Element Value Histogram" + Environment.NewLine + temp2+temp3);
}
}
}
My code won't print the stars match with the value. Could anybody help me?

Try replacing this line:
temp2 += countingNumber + " " + varray[i] + " *" + Environment.NewLine;
with this line:
temp2 += countingNumber + " " + varray[i] + " " + new String('*', i) + Environment.NewLine;

Related

how to calculate totals and minimum spanning trees using arrays

I'm working on a C# assignment in which i have to create a minimum spanning tree through the use of arrays. My code is made up of three arrays which track the nodes and whether or not they have been reached. I have to find the smallest total for all of the randomly generated links to be added up to visit all of the nodes. However, for some reason it is not quite working. The totals being produced are not correct and just wondered if anyone could help me work out why.I believe the error must be between the calculating of the total or how the minimum value is being decided or possible both however i am unsure.
So far i have tried changing the way it is calculated to involve a sum variable to store the values seperately. Ive attempted to add another if statement that would stop the min value from being anything above 98 ( the void value is 99) i have also tried to alter the earlier code to see if how i am testing the values in the SP array are the desired ones. still no results
int n = 5; //n = number of values
int m = 50; //m = max value in arra
int VoidValue = 99; // if i = j value = void value
int Total = 0; //Total value for spanning tree
int sum = 0; //Sum for total value for spanning tree
Random Rand = new Random(); //Create randomise value
int[,] c = new int[n + 1, n + 1]; //Cost array
int[] SP = new int[n + 1]; //Spanned array
int[,] AD = new int[n + 1, n + 1]; //Adjacency array
for (int i = 1; i <= n; i++)
{
SP[i] = 0;
for (int j = 1; j <= n; j++)
{
if (i == j)
{
c[i, j] = VoidValue; // give void spaces the value of 99
AD[i, j] = 0;
}
else
{
c[i, j] = Rand.Next(1, m); // Populate the array with randomised values
AD[i, j] = 0;
}
}
}
//Output all arrays to screen
Console.WriteLine("Cost Array: At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("c[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Spanned Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
// Random Starting Point
int startPoint = Rand.Next(1, n + 1);
Console.WriteLine("Start at node " + startPoint);
SP[startPoint] = 1;
//Check the spanned array
Console.WriteLine("");
Console.WriteLine("Spanned Array : After the starting point has been chosen ");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
// Find minimum vallue link, repeatedly follow these links until spanned array is full
for (int p = 1; p < n; p++) // For every value of the spanned array
{
int MinValue = VoidValue, MinValuei = 0, MinValuej = 0; // declare variables
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++) // I and J are for both variables of the cost and adjacent array
if (i != j)
{
if (SP[i] == 1) //Spanned node
{
if (SP[j] == 0) //Unspanned node
{
if (c[i, j] < MinValue)
{
MinValue = c[i, j];
MinValuei = i;
MinValuej = j;
}
}
}
}
AD[MinValuei, MinValuej] = 1;
SP[MinValuej] = 1;
}
Console.WriteLine("");
Console.WriteLine("The min value is: " + MinValue);
Total = Total + MinValue;
Console.WriteLine("");
Console.WriteLine("The total is: " + Total);
}
//Finally output spanned and adjacent arrays
Console.WriteLine("");
Console.WriteLine("Spanned Array: After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
//Output total value for the spanning tree
Console.WriteLine("");
Console.WriteLine("The total value for the spanning tree: " + Total);
Console.WriteLine("");
Console.ReadLine();

CSV file is not being written to

I am trying to write to a CSV file, and have researched a bit on how to do this and it seems pretty straightforward but it is not populating my CSV file when I run it. The program will write to a txt and my console with no issue.
StreamWriter vWriteFile = new StreamWriter("Positions2.csv");
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}
You should make it a habit to wrap your streams with the using keyword so you don't run into situations where you forget to close it out. It's a good practice to use the using keyword around anything that inherits IDisposable
So your code would look like this.
using(StreamWriter vWriteFile = new StreamWriter("Positions2.csv"))
{
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}
}

Weirdest issue with awesomium and javascript within c#

I am using Awesomium within C# and I am dragging variables out of the javascript within.
The code that is run:
if (GotCategories == false) {
if (WebBrowser.ExecuteJavascriptWithResult("finished").ToString() == "true" && WebBrowser.IsDocumentReady == true) {
int Level1Len = Convert.ToInt32(WebBrowser.ExecuteJavascriptWithResult("all_categories.length").ToString());
for (int i = 0; i < Level1Len - 1; i++) {
string Level1 = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].title");
string Level1ID = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].id");
TreeNode treenode = new TreeNode(Level1);
CatsTree.Nodes.Add(treenode);
int Level2Len = Convert.ToInt32(WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub.length").ToString());
for (int j = 0; j < Level2Len; j++) {
string Level2 = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].title");
string Level2ID = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].id");
treenode = new TreeNode(Level2);
CatsTree.Nodes[i].Nodes.Add(treenode);
int Level3Len = Convert.ToInt32(WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].sub.length").ToString());
for (int k = 0; k < Level3Len; k++) {
string Level3 = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].sub[" + k + "].title");
string Level3ID = WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].sub[" + k + "].id");
treenode = new TreeNode(Level3);
CatsTree.Nodes[i].Nodes[j].Nodes.Add(treenode);
if (WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].sub[" + k + "].sub.length").IsInteger == true) {
string Level4Len = Convert.ToInt32(WebBrowser.ExecuteJavascriptWithResult("all_categories[" + i + "].sub[" + j + "].sub[" + k + "].sub.length").ToString());
A weird issue happens though..
If I run it how it is now Level4Len throws an exception error
Input string was not in a correct format.
Though.. Weirdly enough if I put a MessageBox.Show(Level4Len); I do not receive the error and.. as well as that the outputs that are shown are completely normal as they should be.
Weirdest thing I have seen..

IO exceptional handling (Parameter is not valid)

This is the piece of code i have wriiten. It takes images from the directory and pixel matched it. When the program read 5 images from the directory of same pixels it wor completely fine but when we increase the number of images or images with different pixels it throws the exception "Argumentexcepton was unhandled". Please help
string[] image_name = new string [1000] ;
check = d.GetFiles("*.jpg").Length;
while (imageArray < check)
{
double percentage = 0;
count1 = 0;
count2 = 0;
progressBar1.Value++;
//error occurs on this line
img2 = new Bitmap(image_name[imageArray]);
progressBar1.Maximum = check;
if (img1.Width != img2.Width && img1.Height != img2.Height)
{
if (img2.Width > img1.Width || img2.Height > img1.Height)
{
img1 = ResizeBitmap(img1, img2.Width, img2.Height);
}
else
img1 = ResizeBitmap(img1, img2.Width, img2.Height);
}
for (int i = 0; i < img1.Width; i++)
{
for (int j = 0; j < img1.Height; j++)
{
img1_ref = img1.GetPixel(i, j).ToString();
img2_ref = img2.GetPixel(i, j).ToString();
if (img1_ref != img2_ref)
{
count2++;
break;
}
count1++;
}
}
percentage = (count2 + count1);
percentage = count1 / percentage;
percentage = percentage * 100;
if (percentage < 90)
{
msg1 = "Sorry, Images are not same , " + count1 + " same pixels found and " + count2 + " wrong pixels found";
}
else if (percentage == 100)
{
msg1 = " Images are same , " + count1 + " same pixels found and " + count2 + " wrong pixels found";
ResultImagePanel rmp = new ResultImagePanel(image_name[imageArray], Convert.ToString(percentage) + "%", folderPath + "\\" + image_name[imageArray], msg1);
rmp.Location = new Point(0, 345 * counter);
panel1.Controls.Add(rmp);
}
else
{
msg1 = " Similar images , " + count1 + " same pixels found and " + count2 + " wrong pixels found";
ResultImagePanel rmp = new ResultImagePanel(image_name[imageArray], Convert.ToString(percentage) + "%", folderPath + "\\" + image_name[imageArray], msg1);
rmp.Location = new Point(0, 345 * counter);
panel1.Controls.Add(rmp);
}
counter++;
imageArray++;
}
}
image_name[imageArray] is string.Empty when that code is executed. Hence the error. You will need to fill in the image_name array with valid file names, before executing the code.
Implement your array image_name like this :
image_name = Directory.EnumerateFiles(path, "*.jpg").ToArray();

How can i convert the string to int and count? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
public void Save(string path , string fileName , PictureBox pb)
{
int framesNumberX = 0;
int framesNumberY = 0;
string fn;
string t = Path.GetFileNameWithoutExtension(this.name);
if (File.Exists(path + "\\" + "DATABASE" + "\\" + fileName + "\\" + t + ".txt"))
{
try
{
string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + fileName);
File.Delete(f);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not delete file from disk. Original error: " + ex.Message);
}
fn = path + "\\" + "DATABASE" + "\\" + t + "\\" + fileName;
}
else
{
fn = path + "\\" + "DATABASE" + "\\" + fileName + "\\" + this.name + ".txt";
}
OptionsFile setting_file = new OptionsFile(fn);
setting_file.SetKey("File Name", fn);
setting_file.SetKey("Object Name", fileName);
setting_file.SetKey("Animation Name", this.name);
setting_file.SetKey("picturebox.Width", pb.Width.ToString());
setting_file.SetKey("picturebox.Height", pb.Height.ToString());
string[] xFrames = new string[wocl.Count];
string[] yFrames = new string[wocl.Count];
string X="";
string Y="";
for (int i = 0; i < wocl.Count; i++)
{
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
for (int j = 0; j < wocl[i].Point_X.Count; j++)
{
xFrames[i] += string.Format("{0},", wocl[i].Point_X[j]);
yFrames[i] += string.Format("{0},", wocl[i].Point_Y[j]);
}
string tt = xFrames[i].Trim(",".ToCharArray());
string yy = yFrames[i].Trim(",".ToCharArray());
setting_file.SetKey(X, tt);
setting_file.SetKey(Y, yy);
}
setting_file.SetKey("Number Of Frames X", framesNumberX.ToString());
}
If im doing in the loop for example : FrameNumber +=; it will count me the number of frames for example 6. But i want to count how many times the frames of X showed up and how many frames of Y.
I tried ot it like this:
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
But thats not working not a good way.
Maybe i need to make the counting of X and Y in the end after the variables tt and yy ?
I want to count how many times the loop did the variable tt and how many times it did the variable yy. Just puting int variable and make ++ will give me the overall frames i need to seperate them to X and Y. So if i have for example 6 frames so X will be 3 and Y will be 3.
Convert.Int32() isn't a Val() method, in other words, it won't take just the numbers from any string. When using Convert.Int32(), the entire string has to be numeric, for example:
// doesn't work
string x = "My string 123";
int y = Convert.Int32(x);
// does work
string x = "123";
int y = Convert.Int32(x);
If I understand correctly, you're trying to convert something to an int and count at the same time (here).
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
// blows up with an exception
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
The above could better be written like:
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
framesNumberX++;
framesNumberY++;
// or (depending on what you need)
framesNumberX = i + 1;
framesNumberY = i + 1;
Or - Which would be even more clear; do your math operation first, then use the result in your string.Format() call;
framesNumberX = i + 1;
framesNumberY = i + 1;
X = string.Format("Frame_X_{0} ", framesNumberX);
Y = string.Format("Frame_Y_{0} ", framesNumberY);
However, framesNumberX and framesNumberY would be equal to eachother AND to the iterator i + 1. This is where I'm starting to lose the purpose of the variables. It would help if you could clarify in pseudo-code what exactly you're trying to accomplish:
public void MyMethod()
{
... code here
// trying to `your explanation`
... code here
// and here, I'm trying to `your explanation`
... code here
}
EDIT
for this code to work
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(ExtractNumbers(X));//modfied code line
int d = Convert.ToInt32(ExtractNumbers(Y));//modfied code line
framesNumberX += c; framesNumberY += d;
you need to extract number something like this
static string ExtractNumbers( string expr )
{
return string.Join( null,System.Text.RegularExpressions.Regex.Split( expr, "[^\\d]" ) );
}
Prev Ans
Good way to do is
static void Main()
{
// Convert string to number.
string text = "123";
int num = -1;
if( int.TryParse (text,out num))
Console.WriteLine(num);
}
check that string is convertable or not

Categories