C# Percentage Calculations Not Calculating Properly - c#

I'm developing a simple application which records data and then allows users to retrieve percentages based upon that data. Pass/Fail etc.
My Overall Calculations work just fine but when my 3,6,9 crate calculations take place they don't seem to change even though I've switched which user it should be pulling stats for.
I have changed my code to return a formatted string of the percent calculated in my calc_percent() method. I have also encapsulated my calculations in different methods to make it easier for me to read.
Here is a link to my github project. The project doesn't contain the dataset or tableadapters, I'm thinking my calculation errors could be related to my dataset queries but I'm not sure. I was under the impression that a Fill() method on a table adapter would fill the input dataset with the results of that query. This should allow me to preform further queries to narrow down my results correct? I may be using tableadapter queries improperly but I'm not sure.
#region Metrics Methods
private void generate_stats(User user)
{
int crate_total = 0;
try
{
crate_total = (int)this.CratesTableAdapter.count_crates_by_tech(user.Last_name);
generate_overall_stats(user);
// last 30 units stats
if (crate_total >= 3)
{
generate_3_crate_stats(user);
}
// last 60 units stats
if (crate_total >= 6)
{
generate_6_crate_stats(user);
}
// last 90 units stats
if (crate_total >= 9)
{
generate_9_crate_stats(user);
}
}
catch (NullReferenceException e)
{
MessageBox.Show(e.Message);
}
catch (OleDbException e)
{
MessageBox.Show(e.Message);
}
}
private string calc_percent(int total, int number)
{
double percentage = 0;
percentage = ((double)number / total) * 100;
string format_percent = string.Format("{0:0.00%}", percentage);
try
{
if (percentage == 0)
{
throw new NullReferenceException("Calculation Has Failed, Possible Data Inaccuracy");
}
}catch(NullReferenceException e)
{
MessageBox.Show(e.Message);
}
return format_percent;
}
private void generate_overall_stats(User user)
{
// Overall Stats
int total = (int)this.Audit_ResultsTableAdapter.count_units_by_user(user.Last_name);
int pass = (int)this.Audit_ResultsTableAdapter.count_pass_units_by_user(user.Last_name);
int fail = total - pass;
string ovr_pass_perc = calc_percent(total, pass);
string ovr_fail_perc = calc_percent(total, fail);
metrics_qc_overall_units_display.Text = total.ToString();
metrics_qc_overall_pass_display.Text = ovr_pass_perc;
metrics_qc_overall_fail_display.Text = ovr_fail_perc;
}
private void generate_3_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last30_group.Visible = true;
// Reset data set
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
// Get all crates by user in Desc order according to date (most recent dates at the top of the table)
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
// Get the 3 most recent crates
this.CratesTableAdapter.get_top_3_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_30 = calc_percent(tmp_total, crate_pass);
string fail_percent_30 = calc_percent(tmp_total, crate_fail);
metrics_qc_last30_pass_display.Text = pass_percent_30;
metrics_qc_last30_fail_display.Text = fail_percent_30;
}
private void generate_6_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last60_group.Visible = true;
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
this.CratesTableAdapter.get_top_6_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_60 = calc_percent(tmp_total, crate_pass);
string fail_percent_60 = calc_percent(tmp_total, crate_fail);
metrics_qc_last60_pass_display.Text = pass_percent_60;
metrics_qc_last60_fail_display.Text = fail_percent_60;
}
private void generate_9_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last90_group.Visible = true;
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
this.CratesTableAdapter.get_top_9_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_90 = calc_percent(tmp_total, crate_pass);
string fail_percent_90 = calc_percent(tmp_total, crate_fail);
metrics_qc_last90_pass_display.Text = pass_percent_90;
metrics_qc_last90_fail_display.Text = fail_percent_90;
}
private void set_users_metrics_defaults()
{
metrics_qc_last30_group.Visible = false;
metrics_qc_last60_group.Visible = false;
metrics_qc_last90_group.Visible = false;
}
#endregion
#region Metrics Event Handlers
private void metrics_qc_display_panel_Paint(object sender, PaintEventArgs e)
{
}
private void metrics_auditor_combobox_SelectionChangeCommitted(object sender, EventArgs e)
{
}
private void metrics_qc_combobox_SelectionChangeCommitted(object sender, EventArgs e)
{
set_users_metrics_defaults();
User metrics_user = gen_user_for_metrics();
generate_stats(metrics_user);
}
#endregion

As it stands any crate_total >9 will also evaluate for > 3 and > 6.
if (crate_total >= 3)
if (crate_total >= 6)
if (crate_total >= 9)
You'll need to put upper and lower limits in your if statement.
// last 30 units stats
if (crate_total >= 3 && crate_total < 6)
// last 60 units stats
if (crate_total >= 6 && crate_total < 9)
// last 90 units stats
if (crate_total >= 9)

I changed how I was doing my calculations. The issue was when I would change users the overall stats would change but the 30/60/90 units stats wouldn't change it would always remain the same. I realized that the values weren't being cleared for some reason some way some how (popped into my head while driving). So I segregated everything.
#region Metrics Methods
private void generate_stats(User user)
{
int crate_total = 0;
try
{
crate_total = (int)this.CratesTableAdapter.count_crates_by_tech(user.Last_name);
generate_overall_stats(user);
if (crate_total >= 3)
{
generate_3_crate_stats(user, crate_total);
}
if (crate_total >= 6)
{
generate_6_crate_stats(user, crate_total);
}
//if (crate_total >= 9)
//{
// generate_9_crate_stats(user, crate_total);
//}
}
catch (NullReferenceException e)
{
MessageBox.Show(e.Message);
}
catch (OleDbException e)
{
MessageBox.Show(e.Message);
}
}
private string calc_percent(int total, int number)
{
double percentage = 0;
percentage = ((double)number / total) * 100;
string format_percent = string.Format("{0:0.00}%", percentage);
try
{
if (percentage == 0)
{
throw new NullReferenceException("Calculation Has Failed, Possible Data Inaccuracy");
}
}catch(NullReferenceException e)
{
MessageBox.Show(e.Message);
}
return format_percent;
}
private void generate_overall_stats(User user)
{
// Overall Stats
int total = (int)this.Audit_ResultsTableAdapter.count_units_by_user(user.Last_name);
int pass = (int)this.Audit_ResultsTableAdapter.count_pass_units_by_user(user.Last_name);
int fail = total - pass;
string ovr_pass_perc = calc_percent(total, pass);
string ovr_fail_perc = calc_percent(total, fail);
metrics_qc_overall_units_display.Text = total.ToString();
metrics_qc_overall_pass_display.Text = ovr_pass_perc;
metrics_qc_overall_fail_display.Text = ovr_fail_perc;
}
private void generate_3_crate_stats(User user, int crate_number)
{
metrics_qc_last30_group.Visible = true;
int[] crate_stats = crate_stats_count_3(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_30 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_30 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last30_pass_display.Text = pass_percent_30;
metrics_qc_last30_fail_display.Text = fail_percent_30;
}
private void generate_6_crate_stats(User user, int crate_number)
{
metrics_qc_last60_group.Visible = true;
int[] crate_stats = crate_stats_count_6(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_60 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_60 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last60_pass_display.Text = pass_percent_60;
metrics_qc_last60_fail_display.Text = fail_percent_60;
}
private void generate_9_crate_stats(User user, int crate_number)
{
metrics_qc_last90_group.Visible = true;
int[] crate_stats = crate_stats_count_9(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_90 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_90 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last90_pass_display.Text = pass_percent_90;
metrics_qc_last90_fail_display.Text = fail_percent_90;
}
private void set_users_metrics_defaults()
{
metrics_qc_last30_group.Visible = false;
metrics_qc_last60_group.Visible = false;
metrics_qc_last90_group.Visible = false;
}
private int[] crate_stats_count_3(string last_name, int crate_number)
{
int[] crate_numbers = new int[3];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 3; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
private int[] crate_stats_count_6(string last_name, int crate_number)
{
int[] crate_numbers = new int[6];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
crate_numbers[3] = crate_number -= 3;
crate_numbers[4] = crate_number -= 4;
crate_numbers[5] = crate_number -= 5;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 6; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
private int[] crate_stats_count_9(string last_name, int crate_number)
{
int[] crate_numbers = new int[9];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
crate_numbers[3] = crate_number -= 3;
crate_numbers[4] = crate_number -= 4;
crate_numbers[5] = crate_number -= 5;
crate_numbers[6] = crate_number -= 6;
crate_numbers[7] = crate_number -= 7;
crate_numbers[8] = crate_number -= 8;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 9; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
#endregion
The code shown above calculates hopefully correct percentages based upon count() queries by crate_number / repair_technician. Now when the name is changed in the combo box stats update properly.
With one issue for some reason my 60 and 90 stats remain the same. I haven't looked past finding the bug yet, but I will address it this evening or tomorrow.

Related

ATM program, can't figure out how to break down withdraw amount

First off yes, This is a homework assignment, I've been struggling with it for 3 days, and I can't figure it out.
Basically the problem is to take a decimal amount entered by the user in a text box, I then need to take that number and break it down into currency denominations, $50, $20, $10, $5, $1 and if the amount has a decimal then into
$.25, $.10, $.05, $.01.
And I need to break this down in the lowest amount of denominations possible, for example $100 would be broken down into 2 $50 bills.
Here is what I have so far.
private void btnDispense_Click(object sender, EventArgs e)
{
decimal i;
i = decimal.Parse(txtAmountReq.Text);
decimal totalAmount = Convert.ToDecimal(txtAmountReq);
int[] denomBills = { 50, 20, 10, 5, 1 };
int[] numberOfBills = new int[5];
decimal[] denomCoins = { .25m, .10m, .05m, .01m };
int[] numberOfCoins = new int[4];
//For loop for amount of bills
for (numberOfBills[0] = 0; totalAmount >= 50; numberOfBills[0]++)
{
totalAmount = totalAmount - 50;
}
for (numberOfBills[1] = 0; totalAmount < 20; numberOfBills[1]++)
{
totalAmount = totalAmount - 20;
}
for (numberOfBills[2] = 0; totalAmount < 10; numberOfBills[2]++)
{
totalAmount = totalAmount - 10;
}
for (numberOfBills[3] = 0; totalAmount < 5; numberOfBills[3]++)
{
totalAmount = totalAmount - 5;
}
for (numberOfBills[4] = 0; totalAmount <= 0; numberOfBills[4]++)
{
totalAmount = totalAmount - 1;
}
//For loop for the amount of coins
for (numberOfCoins[0] = 0; totalAmount >= .25m; numberOfBills[0]++)
{
totalAmount = totalAmount - .25m;
}
for (numberOfBills[1] = 0; totalAmount < .10m; numberOfBills[1]++)
{
totalAmount = totalAmount - .10m;
}
for (numberOfBills[2] = 0; totalAmount < .05m; numberOfBills[2]++)
{
totalAmount = totalAmount - .05m;
}
for (numberOfBills[3] = 0; totalAmount < .01m; numberOfBills[3]++)
{
totalAmount = totalAmount - .01m;
}
txt50.Text = Convert.ToString(numberOfBills[0]);
txt20.Text = Convert.ToString(numberOfBills[1]);
txt10.Text = Convert.ToString(numberOfBills[2]);
txt5.Text = Convert.ToString(numberOfBills[3]);
txt1.Text = Convert.ToString(numberOfBills[4]);
txtQuarter.Text = Convert.ToString(numberOfCoins[0]);
txtDime.Text = Convert.ToString(numberOfCoins[1]);
txtNickel.Text = Convert.ToString(numberOfCoins[2]);
txtPenny.Text = Convert.ToString(numberOfCoins[3]);
}
Any help would be greatly appreciated.
This is very famous knapsack type problem.You might want to start exploring from here : https://en.wikipedia.org/wiki/Change-making_problem
The best way to address this problem is to find all possible combinations of change and then find the optimal solution.
Below is the code by karamana I found on codeproject.com :
//find all the combinations
private void findAllCombinationsRecursive(String tsoln,
int startIx,
int remainingTarget,
CoinChangeAnswer answer) {
for(int i=startIx; i<answer.denoms.length ;i++) {
int temp = remainingTarget - answer.denoms[i];
String tempSoln = tsoln + "" + answer.denoms[i]+ ",";
if(temp < 0) {
break;
}
if(temp == 0) {
// reached the answer hence quit from the loop
answer.allPossibleChanges.add(tempSoln);
break;
}
else {
// target not reached, try the solution recursively with the
// current denomination as the start point.
findAllCombinationsRecursive(tempSoln, i, temp, answer);
}
}
}
in order to find optimum solution :
public CoinChangeAnswer findOptimalChange(int target, int[] denoms) {
CoinChangeAnswer soln = new CoinChangeAnswer(target,denoms);
StringBuilder sb = new StringBuilder();
// initialize the solution structure
for(int i=0; i<soln.OPT[0].length ; i++) {
soln.OPT[0][i] = i;
soln.optimalChange[0][i] = sb.toString();
sb.append(denoms[0]+" ");
}
// Read through the following for more details on the explanation
// of the algorithm.
// http://condor.depaul.edu/~rjohnson/algorithm/coins.pdf
for(int i=1 ; i<denoms.length ; i++) {
for(int j=0; j<target+1 ; j++) {
int value = j;
int targetWithPrevDenomiation = soln.OPT[i-1][j];
int ix = (value) - denoms[i];
if( ix>=0 && (denoms[i] <= value )) {
int x2 = denoms[i] + soln.OPT[i][ix];
if(x2 <= target && (1+soln.OPT[i][ix] < targetWithPrevDenomiation)) {
String temp = soln.optimalChange[i][ix] + denoms[i] + " ";
soln.optimalChange[i][j] = temp;
soln.OPT[i][j] = 1 + soln.OPT[i][ix];
} else {
soln.optimalChange[i][j] = soln.optimalChange[i-1][j]+ " ";
soln.OPT[i][j] = targetWithPrevDenomiation;
}
} else {
soln.optimalChange[i][j] = soln.optimalChange[i-1][j];
soln.OPT[i][j] = targetWithPrevDenomiation;
}
}
}
return soln;
}
Link to the original code here

How to convert collection arrays to list<> C#

I have several arrays to collect data from a postgreSQL query. The data comes from RF receiver deployed in the field. As the user establishes the range of frequencies and time for the query the data is displayed on gridview and passed from there to the arrays indicated by an I value and a I + value matching the cell number in the column containing the latitude of the RF receiver. This data is use to plot xy scatter graphs representing (frequency,amplitude), (frequency,bandwidth) etc. I would like to create a list and objects instead of using arrays.
private void button11_Click(object sender, EventArgs e)
dataGridView1.SelectAll();
numCells = dataGridView1.SelectedCells.Count;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()== 28.464258839)
{
UCS1size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.42859146)
{
MOCsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.490616471)
{
AMsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.525409911)
{
UCS2size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.560529988)
{
LC40size += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
double[] freqLC40 = new double[LC40size];
double[] ampMaxLC40 = new double[LC40size];
double[] freqMOC = new double[MOCsize];
double[] ampMaxMOC = new double[MOCsize];
double[] freqUCS1 = new double[UCS1size];
double[] ampMaxUCS1 = new double[UCS1size];
double[] freqUCS2 = new double[UCS2size];
double[] ampMaxUCS2 = new double[UCS2size];
double[] freqAM = new double[AMsize];
double[] ampMaxAM = new double[AMsize];
int LC40idx = 0;
int MOCidx = 0;
int UCS1idx = 0;
int UCS2idx = 0;
int AMsidx = 0;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString())== 28.464258839)
{
freqUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCell[i].Value.ToString());
ampMaxUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS1idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i +11].Value.ToString()) == 28.42859146)
{
freqMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
MOCidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.490616471)
{
freqAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i + 9].Value.ToString());
AMsidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.525409911)
{
freqUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS2idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.560529988)
{
freqLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i+9].Value.ToString());
LC40idx += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
//get XY form LC40
xyForm = new XYplotForm();
xyForm.Plot(freqLC40, ampMaxLC40, "LC-40 Max Amplitude");
xyForm.Show();

Generate all unique bank account numbers

I have a method that checks if a number is divisible by 11.
public bool IsBankAccount(string BankNumber)
{
int factor = 9;
int restult = 0;
try
{
if ((BankNumber.Length == 9))
{
for (int i = 0; i < BankNumber.Length; i++)
{
restult += int.Parse(BankNumber.Substring(i, 1)) * factor;
factor -= 1;
}
return (restult % 11 == 0);
}
else
{
//Wrong length;
return false;
}
}
catch (Exception)
{
return false;
}
}
But how to generate all the first bank account numbers that is a bank number, the first number is:
100000002 = because 9*1 + 8*0 + 7*0 +6*0 + 5*0 + 4*0 + 3*0 + 2*0 + 1*2 = 11
And if you want all the bank account numbers. THere are 1000 000 000 numbers in a 9 digit numbers. so 1000 000 000/11 = 90909090.9 11-eleven numbers
I just try different solutions.
but if I try this:
static readonly int[] multipliers = {9, 8, 7, 6, 5, 4, 3, 2, 1};
static void Main(string[] args)
{
var bansAsStrings = BANS().Take(100).Select(ban => ban.ToString());
foreach (var ban in bansAsStrings)
{
Console.WriteLine(ban);
}
Console.ReadKey();
}
static IEnumerable<int> BANS()
{
int[] digits = { 1, 0, 0, 0, 0, 0, 0, 0, 2 };
int carryFlag = 0;
do
{
int sum = digits.Zip(multipliers, (d, m) => d * m)
.Sum();
if (sum % 11 == 0)
yield return sum;
int digitIndex = digits.Length - 1;
do
{
digits[8] += 1 + carryFlag;
if (digits[8] == 10)
{
digits[digitIndex--] = 0;
carryFlag = 1;
}
else
carryFlag = 0;
}
while (carryFlag == 1 && digitIndex >= 0);
}
while (carryFlag == 0);
yield break;
}
the output is 11 100 times.
I have it now like this:
static void Main(string[] args)
{
const int linesPerFile = 10;
const string destinationFileName = #"G:\Folder\File-Part-{0}.txt";
//string fileName = "File";
foreach (var bank in BankAcoutNumbers.BANS.Take(200))
{
var fileCounter = 0;
var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while ((line = destiNationFile.NewLine) != null )
{
if (lineCounter >= linesPerFile)
{
lineCounter = 0;
fileCounter++;
destiNationFile.Dispose();
destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
}
destiNationFile.WriteLine(bank);
lineCounter++;
}
//}
}
catch (Exception)
{
throw;
}
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
But now every time it writes the first value: 1000 000 02
I have it now like this:
static void Main(string[] args)
{
const int linesPerFile = 10;
const string destinationFileName = #"G:\Folder\File-Part-{0}.txt";
//string fileName = "File";
var maxNumberOfFiles = 20;
var fileCounter = 0;
var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while (fileCounter < maxNumberOfFiles)
{
foreach (var bank in BankAcoutNumbers.BANS.Take(200))
{
if (lineCounter >= linesPerFile)
{
lineCounter = 0;
fileCounter++;
destiNationFile.Dispose();
destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
}
destiNationFile.WriteLine(bank);
lineCounter++;
}
fileCounter++;
//}
}
}
catch (Exception)
{
throw;
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
But I dont like that you every time have to calculate the number of MaxFiles. Is there an other way to go? Thanks
Here is an update:
static void Main(string[] args)
{
const int linesPerFile = 10;
string path = #"G:\Folder";
const string destinationFileName = #"G:\Folder\File-Part-{0}.txt";
//string fileName = "File";
var maxNumberOfFiles = 10;
Stopwatch timer = new Stopwatch();
var fileCounter = 0;
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while (fileCounter <= maxNumberOfFiles)
{
timer.Start();
foreach (var bank in BankAcoutNumbers.BANS.Take(100))
{
if (lineCounter % linesPerFile == 0)
{
//lineCounter = 0;
destiNationFile.Flush();
destiNationFile.Dispose();
destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
fileCounter++;
}
destiNationFile.WriteLine(bank);
lineCounter++;
}
fileCounter++;
//}
}
timer.Stop();
// Console.WriteLine(BankAcoutNumbers.BANS.Count());
Console.WriteLine(timer.Elapsed.Seconds);
}
catch (Exception)
{
throw;
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
But to get the file names, like this: Nr[first number in file]-[last number in file].txt Thank you
I have it now like this:
static void Main(string[] args)
{
const int linesPerFile = 10;
string path = #"G:\Folder";
const string destinationFileName = #"G:\Folder\File-Part-{0}.txt";
var bans = BankAcoutNumbers.BANS;
var counter = 100;
string tempFile;
//string fileName = "File";
var maxNumberOfFiles = 10;
Stopwatch timer = new Stopwatch();
var fileCounter = 0;
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while (fileCounter <= maxNumberOfFiles)
{
timer.Start();
foreach (var bank in bans)
{
if (--counter == 0)
{
break;
}
if (lineCounter % linesPerFile == 0)
{
//lineCounter = 0;
destiNationFile.Flush();
destiNationFile.Dispose();
destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
fileCounter++;
}
destiNationFile.WriteLine(bank);
lineCounter++;
fileCounter++;
//}
}
}
timer.Stop();
// Console.WriteLine(BankAcoutNumbers.BANS.Count());
Console.WriteLine(timer.Elapsed.Seconds);
}
catch (Exception)
{
throw;
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
but then every time the last file of the ten files is empty.
And how to get the file names?
static void Main(string[] args)
{
const int linesPerFile = 10;
string path = #"G:\Folder";
//string fileName = string.Format("{0}{1}-", part[0], part[part.Count - 1]);
var bans = BankAcoutNumbers.BANS;
string tempFile;
const int MAX_FILES = 10;
const int BANS_PER_FILE = 10;
int bansCounter = 0;
var part = new List<int>();
string fileName = string.Format("{0}-{1}", part[0], part[part.Count - 1]);
var maxNumberOfFiles = 10;
Stopwatch timer = new Stopwatch();
var fileCounter = 0;
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
//var destiNationFile = new StreamWriter(string.Format(fileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while (fileCounter <= maxNumberOfFiles)
{
timer.Start();
foreach (var bank in BankAcoutNumbers.BANS)
{
part.Add(bank);
if(++bansCounter >= BANS_PER_FILE)
{
//string fileName2 = string.Format("{0}-{1}", part[0], part[part.Count - 1]);
var destinationFile = new StreamWriter(fileName);
//destiNationFile = new StreamWriter(fileName);
Console.WriteLine("NR{0}", fileName);
foreach (var partBan in part )
Console.WriteLine(partBan);
part.Clear();
bansCounter = 0;
if (++fileCounter >= MAX_FILES)
break;
//lineCounter = 0;
//destiNationFile.Flush();
//destiNationFile.Dispose();
//destiNationFile = new StreamWriter(string.Format(fileName, fileCounter + 1));
//fileCounter++;
}
//destiNationFile.WriteLine(bank);
//lineCounter++;
}
//fileCounter++;
//}
}
timer.Stop();
// Console.WriteLine(BankAcoutNumbers.BANS.Count());
Console.WriteLine(timer.Elapsed.Seconds);
}
catch (Exception)
{
throw;
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
public static IEnumerable<int> BANS
{
get
{
int[] digits = { 1, 0, 0, 0, 0, 0, 0, 0, 2 };
int carryFlag = 0;
do
{
int sum = digits.Select((d, i) => d * (9 - i))
.Sum();
if (sum % 11 == 0)
yield return digits.Aggregate(0, (accumulator, digit) => accumulator * 10 + digit);
int digitIndex = digits.Length - 1;
do
{
digits[digitIndex] += 1;
if (digits[digitIndex] == 10)
{
digits[digitIndex--] = 0;
carryFlag = 1;
}
else
carryFlag = 0;
}
while (digitIndex >= 0 && carryFlag == 1);
}
while (carryFlag == 0);
yield break;
}
}
Console.WriteLine(BANS.Count()) gives 81818182 BAN's. The calculation time about 5 minutes in the virtual machine.
First 10 values are:
foreach (var ban in BANS.Take(10))
Console.WriteLine(ban);
----------------------------------
100000002
100000010
100000029
100000037
100000045
100000053
100000061
100000088
100000096
100000118
On the second question:
static void Main(string[] args)
{
const int MAX_FILES = 10;
const int BANS_PER_FILE = 10;
int filesCounter = 0;
int bansCounter = 0;
var part = new List<int>();
foreach (var ban in BANS)
{
part.Add(ban);
if (++bansCounter >= BANS_PER_FILE)
{
string fileName = string.Format("{0}-{1}.txt", part[0], part[part.Count - 1]);
Console.WriteLine("Filename '{0}'", fileName);
foreach (var partBan in part)
Console.WriteLine(partBan);
part.Clear();
bansCounter = 0;
if (++filesCounter >= MAX_FILES)
break;
}
}
}
You can enumerate the possible numbers by calculating the last digit as a check digit:
static void Main(string[] args)
{
foreach (var num in GetMod11Sequence(10000000, 100000000).Take(100))
{
if (!CheckMod11CheckChar(num))
{
throw new InvalidOperationException();
}
else
{
Console.WriteLine(num);
}
}
}
private static IEnumerable<string> GetMod11Sequence(int start, int stop)
{
//Contract.Requires(start > 0);
//Contract.Requires(stop > start);
//Contract.Requires(stop < 1000000000);
for (int c = start; c < stop; c++)
{
string number = c.ToString();
char check;
if (TryCalculateMod11CheckChar(number, out check))
{
yield return number + check;
}
}
}
private static bool CheckMod11CheckChar(string number)
{
//Contract.Requires(number != null);
//Contract.Requires(number.All(c => char.IsDigit(c)));
int factor = number.Length;
int sum = 0;
for (int i = 0; i < number.Length; i++)
{
int cval = number[i] - '0';
sum += cval * factor;
factor--;
}
return sum % 11 == 0;
}
private static bool TryCalculateMod11CheckChar(string number, out char checkDigit)
{
//Contract.Requires(number != null);
int factor = number.Length + 1;
int sum = 0;
for (int i = 0; i < number.Length; i++)
{
int cval = number[i] - '0';
sum += cval * factor;
factor--;
}
//Contract.Assert(factor == 1);
int delta = sum % 11;
if (delta == 1)
{
// I cannot add 10, so this number is unavailable
checkDigit = '!';
return false;
}
else
{
if (delta == 0)
{
checkDigit = '0';
}
else
{
checkDigit = (11 - delta).ToString()[0];
}
return true;
}
}
Is this what you want?
var bankAccounts = new List<string>(100);
for(long i = 100000000; bankAccounts.Count < 100;i++)
{
var stringNumber = i.ToString();
if (IsBankAccount(stringNumber))
bankAccounts.Add(stringNumber);
}
This can be also done with LINQ as follows.
var accounts = Enumerable.Range(100000000, 2000) // 2000 is a guess, there's sure 100 values divisible by 11 in that range
.Select(n => n.ToString())
.Where(IsBankAccount)
.Take(100)
.ToList();
As there are only numbers in bank account, you could probably do it without string conversions and string operation.
To get all of them, replace 2000 with 899999999, but it will take a long time to finish even if you do it .AsParallel() because the algorithm is really ineffective.
Based on a comment from ie, a fast algorithm could look like this, but it's still very memory consuming.
var nums = new List<string>();
for (int i = 100000002; i < 1000000000; i += 11)
nums.Add(i.ToString());

Conversion of Binary fractions to Decimal in C# GUI

How do you convert binary fractions to decimal in c#? eg: 1101.101 is supposed to be 13.625, I get 1.25 which is way off. I seem to get errors when I put a fractional binary number, no problems on whole Binary numbers. I can show my code if needed.
Code:
double tempans = 0;
double answer = 0;
string finAns;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] temp = new string[5];
string strHldr = textBox1.Text;
bool isFractional = strHldr.Contains('.');
double val1 = 0;
double val2 = 0;
if (!isFractional)
finAns = ComputePart(strHldr);
else
{
string wholeP = WholePart(strHldr);
string deciP = DecimalPart(strHldr);
val1 = double.Parse(ComputePart(wholeP));
val2 = double.Parse(ComputeDeci(deciP));
finAns = (val2 + val2).ToString();
}
textBox1.Text = finAns;
}
private string ComputePart(string strHldr)
{
double length1 = strHldr.Length - 1;
for (int i = 0; i < strHldr.Length; i++)
{
if (strHldr[i] == '1')
{
tempans = Math.Pow(2, length1);
answer += tempans;
}
length1 -= 1;
}
length1 = 0;
return answer.ToString();
}
private string ComputeDeci(string number)
{
double ans = 0;
double counter = 1;
double finalAns = 0;
for (int i = 0; i < number.Length; i++)
{
ans = counter * 0.5;
counter = ans;
if (number[i] == '1')
{
finalAns += counter;
}
}
return finalAns.ToString();
}
private string DecimalPart(string number)
{
int numCut = number.IndexOf('.');
return number.Substring(numCut + 1);
}
private string WholePart(string number)
{
return ((int)Math.Floor(double.Parse(number))).ToString();
}
}
}
It's just a typo in your code:
finAns = (val2 + val2).ToString();
should be
finAns = (val1 + val2).ToString();
Note that val2 was added to val2 rather than val1 being added to val2.

get the value from the dictionary

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.

Categories

Resources