namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;
string[] doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int[] systolic = new int[5];
int[] diastolic = new int[5];
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}
//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;
doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
}
}
}
}
}
This is the file it is getting it from
When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).
I've tried resetting the array at the end of the loop but that solves nothing
Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.
Like this:
string name = inputFile.ReadLine();
//Calculates average for systolic
double total = 0;
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
double average_sys = total / 5;
int doctor = int.Parse(inputFile.ReadLine());
string DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
Even better, use var instead of setting the variable type in two places and risking getting it wrong.
You're not resetting your variables for total and average for the second set of measurements.
Related
The system needs a way of taking input from txtBox.
I then need the system to take the number input, 1-10. And repeat the ticket and file creation for that x amount of times.
This code also creates a file on the pc with the Lottery ticket in it.
the files have to be named LottoKupon1, LottoKupon2 and so on, this needs to match user input of course.
this is for creation of file and folder
namespace Lottery
{
internal class FolderCreater
{
static string folderName = #"C:\lotto";
public static string fileName = #"C:\lotto\LottoKupon.txt";
public static void CreateFolder()
{
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
else if (!File.Exists(fileName))
{
File.Create(fileName);
}
else { }
}
}
}
This is for creation of Lottry Ticket
namespace Lottery
{
// the system needs a way of taking input
// from txtBox, int user = int.Parse(txtBox.Text.Trim()); which this line does
// i then need the system to take the number input, 1-10.
// and repeat the ticket and file creation for that x amount of times.
public partial class MainWindow : Window
{
public List<long> ListOfAllArrays = new List<long>();
int i = 1;
Random randNum = new Random();
public MainWindow()
{
InitializeComponent();
}
public void Lotto ()
{
StreamWriter sw = new StreamWriter(FolderCreater.fileName);
sw.WriteLine(" " + "Lotto " + DateTime.Now.ToString("dd/MM/yyyy\n"));
sw.WriteLine(" " + "1-uge\n" + " LYN-LOTTO\n");
Random randNum = new Random();
int[][] AllArrays = new int[10][];
for (int i = 0; i < 10; i++)
{
AllArrays[i] = new int[7];
}
int RowNr = 0;
foreach (int[] row in AllArrays)
{
RowNr++;
sw.Write(RowNr + ". ");
for (int j = 0; j < 7; j++)
{
int number = randNum.Next(1, 37);
while (row.Any(n => n == number))
{
number = randNum.Next(1, 37);
}
row[j] = number;
}
Array.Sort(row);
for(int l = 0; l < 7; l++)
{
sw.Write(row[l].ToString("00") + " ");
}
sw.Write("\n");
}
TestIfSame(AllArrays);
if (CheckBox.IsChecked == true)
{
sw.WriteLine("\n****** Joker Tal ******");
int[][] AllJokerRows = new int[2][];
for (int i = 0; i < 2; i++)
{
AllJokerRows[i] = new int[7];
}
foreach (int[] n in AllJokerRows)
{
sw.Write(" ");
for (int i = 0; i < 7; i++)
{
var JokerNumber = randNum.Next(1, 10);
n[i] = JokerNumber;
}
Array.Sort(n);
for (int u = 0; u < 7; u++)
{
sw.Write(n[u] + " ");
}
sw.Write("\n");
}
}
sw.Close();
}
public void TestIfSame(int[][] AllArrays)
{
//List<long> ListOfAllArrays = new List<long>();
for (int i = 0; i < AllArrays.Length; i++)
{
ListOfAllArrays.Add(MakesLongNumber(AllArrays[i]));
}
for (int i = 0; i < AllArrays.Length; i++)
{
long temp = ListOfAllArrays[0];
ListOfAllArrays.Remove(ListOfAllArrays[0]);
if (ListOfAllArrays.Contains(MakesLongNumber(AllArrays[i])))
{
Lotto();
}
else
{
ListOfAllArrays.Add(temp);
}
}
long MakesLongNumber(int[] row)
{
string a = "";
for (int i = 0; i < row.Length; i++)
{
a += row[i].ToString();
}
return Convert.ToInt64(a);
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void cmdOk_Click_1(object sender, RoutedEventArgs e)
{
FolderCreater.CreateFolder();
Lotto();
// add a ListBox.Items.Add(); within this needs to be the command for the Lottery ticket, so i can have it shown on a list box.
}
**This is for a Lottery assignment, its on a lower level of coding, so no answer that is way too complicated, hope you understand. please ask questions if needed.
I tried a dew things with a for loop around the first void which took user input, but i could not make it work.
the code is expected to create files and Lottery ticket depending on users input**
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
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.
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
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;
}